views:

106

answers:

3

I am writing a web service to expose certain pieces of data to one of our third party applications. Their team requires a generic way to retrieve values of fields in our system. I have written a class where the only public members of the class are the values they need. What I would like to do is have them pass an enumerated string that is the name of the member they want to retrieve and if it is a valid name of a public member, return the value of that member. I was messing around with some of the reflection methods in .net but can't quite get the behavior I am looking for. I am trying to write something to recreate the functionality of this pseudo code:

public Object webserviceMethodToReturnValue(Guid guidOfInternalObject, String nameOfProperty)
{
    internalObject obj = new internalObject(guid); //my internal company object, which contains all the public members the external company will need
    Object returnObject = obj.{nameOfProperty}; //where name of property is evaluated as the name of the member of the internalOject
    return returnObject; //returning an object that could be casted appropriately by the caller
}

So that you could call the service like:

String companyName = (String)webserviceMethodToReturnValue(guid, "companyName");
+4  A: 

You need to call the GetProperty method, like this:

PropertyInfo property = typeof(InternalObject).GetProperty(nameOfProperty);
return property.GetValue(obj, null);

Beware that it won't be very fast.

To make it faster, you could use expression trees in .Net 3.5 to create statically-typed methods at runtime that return the values.

SLaks
Exactly right. I had been able to suss out everything except the need for GetValue. Thank you.
kscott
A: 

Yep! you would do this: typeof(InternalObject).GetProperty(nameOfProperty).GetValue(obj,null)

Erich
+1  A: 

Reflection!

BlueRaja - Danny Pflughoeft