Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of a specific object property in C# without knowing the class behind

Tags:

c#

.net

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; 
like image 507
uhu Avatar asked Jul 09 '12 12:07

uhu


People also ask

What is GetProperty C#?

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.

What is GetValue in C#?

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.


2 Answers

Use reflection

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name"); String name = (String)(pi.GetValue(item, null)); 
like image 172
Waqar Avatar answered Oct 20 '22 14:10

Waqar


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.

like image 38
Eren Ersönmez Avatar answered Oct 20 '22 14:10

Eren Ersönmez