Reflection: How to discover name of a property at run time.

V

Victor

Is it a way to discover, at the run time, the name of a property of an object?
In other words is it possible to create a method GetPropertyName, that takes
a property of an object and returns the name of that property? So:

string name = GetPropertyName(int.MaxValue); // returns “MaxValueâ€
string name = GetPropertyName(DateTime.Now); // returns “Nowâ€

(Something similar exists to
System.Reflection.MethodInfo.GetCurrentMethod().Name; that returns the name
of the current method)
 
D

Duggi

Is it a way to discover, at the run time, the name of a property of an object?
In other words is it possible to create a method GetPropertyName, that takes
a property of an object and returns the name of that property? So:

string name = GetPropertyName(int.MaxValue); // returns “MaxValue”
string name = GetPropertyName(DateTime.Now); // returns “Now”

(Something similar exists to
System.Reflection.MethodInfo.GetCurrentMethod().Name; that returns the name
of the current method)


Try the following snippet of code..

Type myType = tc.GetType();
PropertyInfo[] allPropertiesInfo = myType.GetProperties();

foreach (PropertyInfo pInfo in allPropertiesInfo)
{
Console.WriteLine(((System.Reflection.MemberInfo)(pInfo)).Name);
}

Hope this would be useful.

-Cnu
 
V

Victor

It does exactly what I have wished for!

Looks a bit scary, but it does the job.

The reason I been looking for that functionality is similar to the one
described in the post you referred to.
In my LINQ to SQL buz layer, to report errors, I have to name LINQ entity
properties to blame as a reason for error.
" .... at the moment I use strings, but if the property name on the class
changes it causes runtime errors whereas I would prefer compile time errors.
To be clear, I want the name of the property and not the value of a property
of an instance. "

The other place where I wished for it, is custom data binding, like
MyFantasticBinfd(this.Textxbox1, LINQEntity, "Property1"), where again
Propert1 is a string, and changes to LINQEntity wouldn't be recognized by
compiler.

Please let my voice to JOIN to those who are looking for the nameof(...)
operator.

Victor
 
V

Victor

Marc,

thanks again for your reply. Using your code I was able to replace:

AddBusinessError("cs_dt_received", "Received date can't be earlier than date
of loss");
to
AddBusinessError<T_ComplainCase, DateTime?>(x => x.cs_dt_received, "Received
date can't be earlier than date of complain");

where T_ComplainCase is LINQ to SQL autogenerated class, and cs_dt_received
is one of the properties (i.e. SQL server table's column). This is much
better for me, since now I can be sure that if somebody changes table on SQL
server my code fails when compile.

My question, in you is:
In your post
http://groups.google.com/group/micr...read/thread/f44dc57a9dc5168d/4805324df6b30218 you have mentioned that:

"In fact, add in some "this TType obj" and you get type inference... ".
string test1 = foo.MemberName(x => x.Bar);

Can you share that code with us?

Thanks Victor.
 
M

Marc Gravell

I haven't checked (in a hurry), but:

public static string MemberName<TType>(
this TType type,
Expression<Action<TType>> member)
{
return MemberInfo(member).Name;
}

public static string MemberName<TType, TResult>(
this TType type,
Expression<Func<TType, TResult>> member)
{
return MemberInfo(member).Name;
}

The "type" argument isn't used except by the compiler for the type-
inference.

Marc
 
M

Marc Gravell

Looks a bit scary, but it does the job.

That phrase pretty-much describes most manual uses of Expression - a
very confusing subject indeed! For info, though: it looks scary, but
it gets easier with a little practice - you just need to take a very
deep breath before diving in ;-p

Marc
 
V

Victor

And they worth diving in!

After looking at your elegant code I’ve realized how important Expressions
might be, and definitely want to spend some time learning more.

Also, when I have incorporated it in my application, I do not see it any
more “as largely "for jollies"â€. I feel much more confident in biasness logic
layer now, than when the database fields (i.e. SQL LINQ properties) where
strings in my error reporting methods.

Since my original question was about getting names of the properties, I have
modified your code and introduced a delegate that returns object, so when
looking for a property name, I do not need to specify result type <TType,
TResult>, but just <TType>.

Actually, your code blows on such expressions, since Expression contains
Convert function that your code doesn’t expect ({x =>
Convert(x.cs_dt_received)}).

In the code below expression parsing is 'hard wired' (just for
illustration), so the place for UnitaryExpression is visible.

static class MemberUtil
{

public delegate object PropertyNameDeletgate<T>(T x);

public static string GetPropertyName<T> (Expression
<PropertyNameDeletgate<T>> member)
{
return ((MemberExpression) ((Expression) ((UnaryExpression)
member.Body).Operand)).Member.Name;
//return MemberUtil.ParseMemberInfo(member).Name;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top