views:

213

answers:

5

I want to supply unknown "object" and return the value of one of its members. Response is required in C#.

Generically I guess I'm looking for the code to this method public static object GetObjectMemberValue (object myObject, string memberName)

More specifically I'm doing this for resource strings in Silverlight and need to write this method. It resides in a common project is used against a few different Resx dictionaries, thus I don't have access to the type information. public static string GetString (object StringResources, string ResourceId)

Thank you!

+1  A: 

if you know the objects type, then cast to it?

Or it should at least implement an interface if you don't know the explicit type?

MyType value = (MyType)objectGetter() //this is the function that returns the unknown.
value.GetMember()
Spence
A: 

First get the type of the object:

Type myObjectType = myObject.GetType();

Then, you can use the returned Type object to get the property's info, and then it's value.

MiffTheFox
+5  A: 

This will get your value... Can you give me more info in the resx part of the question?

public static object GetObjectMemberValue(object myObject, string memberName)
{
  PropertyInfo dateProperty = myObject.GetType().GetProperty(memberName);
  return dateProperty.GetValue(myObject, null);
}
russau
That's all I needed. Thanks Russau. The resx part is a hack not worth explaining. Its just a crappy workaround I've created because Silverlight 2.0 doesn't allow me include resource dictionaries (xaml) across multiple Silverlight class library projects. Merged dictionaries were supported in Silverlight 3.0 and when I migrate I can get rid of this hack. Reflection is cool but I totally agree with some of the other comments in that it should be avoid when you can strongly type an object.
Justin
+1  A: 
static class ObjectExtensions {
    public static object GetObjectPropertyValue(this object o, string propertyName) {
        return o.GetType().GetProperty(propertyName).GetValue(o, null);
    }
}

class Test {
    public string Message {get; set;}
}

class Program {
    static void Main(string[] args) {
        object t = new Test { Message = "Hello, World!" };
        Console.WriteLine(t.GetObjectPropertyValue("Message").ToString());
    }
}
Jason
please don't write extension methods on object. Create an interface and write the extension method on that.
Robert
I agree with you, that is the right way to do it.
Jason
A: 
o.GetType().InvokeMember( "MemberName", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, o, null );
Paul Alexander