34

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;
uhu
  • 1,702
  • 5
  • 17
  • 26
  • 1
    GetValue(item, "PropertyName") – Alex Jul 09 '12 at 12:48
  • 1
    You can use `System.Reflection` to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - http://www.switchonthecode.com/tutorials/csharp-tutorial-using-reflection-to-get-object-information – JMK Jul 09 '12 at 12:50
  • 1
    Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something. – tbddeveloper Jul 09 '12 at 12:51

7 Answers7

69

Use reflection

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
Waqar
  • 2,511
  • 18
  • 15
65

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.

Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
8

Reflection can help you.

var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
Maarten
  • 22,527
  • 3
  • 47
  • 68
5

Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

  object value = GetValue();
  string propertyName = "MyProperty";

  var parameter = Expression.Parameter(typeof(object));
  var cast = Expression.Convert(parameter, value.GetType());
  var propertyGetter = Expression.Property(cast, propertyName);
  var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing

  var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();

 var retrivedPropertyValue = propertyRetriver(value);

This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

Rafal
  • 12,391
  • 32
  • 54
2

In some cases, Reflection doesn't work properly.

You could use dictionaries, if all item types are the same. For instance, if your items are strings :

Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);

Or ints:

Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
Dugh
  • 171
  • 1
  • 3
  • This is exactly what I needed. Much nicer to work with than reflection! In my case I had a serialized JSON value and was attempting to De-Serialize it as an object and then use reflection to read the object property values. The results were always null for some reason though, but this answer was the solution! – Hedgybeats Jan 17 '23 at 09:12
2

You can do it using dynamic instead of object:

dynamic item = AnyFunction(....);
string value = item["name"].Value;
San
  • 21
  • 2
0

Simply try this for all properties of an object,

foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
   var propertyName = prop.Name;
   var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);

   //Debug.Print(prop.Name);
   //Debug.Print(Functions.convertNullableToString(propertyValue));

   Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
}

NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.

Haseeb Ahmed
  • 235
  • 2
  • 11