I have an instance of the Account
class. Each account object has an owner, reference, etc.
One way I can access an accounts properties is through accessors like
account.Reference;
but I would like to be able to access it using dynamic string selectors like:
account["PropertyName"];
just like in JavaScript. So I would have account["Reference"]
which would return the value, but I also would like to be able to assign a new value after that like:
account["Reference"] = "124ds4EE2s";
I've noticed I can use
DataBinder.Eval(account,"Reference")
to get a property based on a string, but using this I can't assign a value to the property.
Any idea on how I could do that?
You need to use Reflection:
Note that this will be very slow.
If they are your own objects you could provide an indexer to access the fields. I don't really recommend this but it would allow what you want.
Note that you lose type safety when doing this.
If you are using .Net 4 you can use the dynamic keyword now.
I used the reflection method from Richard, but elaborated the set method to handle other types being used such as strings and nulls.
The SetValue() function will throw an error if the conversion doesn't work.
You could try combining the indexer with reflection...
First of all, you should avoid using this; C# is a strongly-typed language, so take advantage of the type safety and performance advantages that accompany that aspect.
If you have a legitimate reason to get and set the value of a property dynamically (in other words, when the type and/or property name is not able to be defined in the code), then you'll have to use reflection.
The most inline-looking way would be this:
However, you can cache the
PropertyInfo
object to make it more readable: