Alex Rivera | Logout

Is it possible to get an object property name string without creating the object instance?

Asked 2011-11-15T12:41:00.580
16

A string representation of an object instance property can be taken with Expression<Func<T>>:

string propertyName = ((MemberExpression) property.Body).Member.Name;

But what if I don't have (don't want to create) the instance? How do I get the property name in this case?

Explained

I need a string representation of a property name of some object.

Let's say there is an entity

public class Customer
{
    public int ID;
    public string Name;
}

Now I want to pass the key expression of this entity to some other function, thus I need the string "ID", but I don't want to hardcode the string like SomeOtherFunction("ID"), instead I use the expression SomeOtherFunction(ExpressionReader.GetString(() => CustomerInstance.ID)). For this to work I need to supply the entity instance.

Now I want to do the same without creating the instance.

Edit
Report

1 Answer

1

I'm not sure I fully understand what you mean, but based on my understanding you could use Reflection. Using this approach, if you had the Type of what you wanted to get a property name from, then you could retrieve the properties using:

Type someType = typeof(SomeClass);

// Get all properties for a type
PropertyInfo[] properties = someType.GetProperties();

// Get a property from a type by it's name
PropertyInfo property = someType.GetProperty("PropertyName");

Once you have instance(s) of the PropertyInfo class, you can retrieve information such as the property name.

For more information on this approach, see the MSDN Documentation.

answered 2011-11-15T12:51:43.597

Your Answer