I have an object (.NET) of type "object". I don't know the "real type (class)" behind it during runtime , but I know, that the object has a property "string name". How can I retrive the value of "name"? Is this possible?
something like this:
object item = AnyFunction(....); string value = item.name;
GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints. GetProperty(String) Searches for the public property with the specified name.
The GetValue() method of array class in C# gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer. We have set the array values first using the Array.
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name"); String name = (String)(pi.GetValue(item, null));
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....); string value = item.name;
Note that the Dynamic Language Runtime (DLR) has built-in caching mechanisms, so subsequent calls are very fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With