473,473 Members | 1,419 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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

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().Na me; that returns the name
of the current method)

Aug 17 '08 #1
9 1931
On Sat, 16 Aug 2008 21:23:00 -0700, Victor
<Vi****@discussions.microsoft.comwrote:
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().Na me; that returns the
name
of the current method)
MethodInfo.GetCurrentMethod() is only useful when called from _within_ the
method in question. That's completely different from the example lines of
code you posted, so it's very difficult to understand exactly what you
want to do.

That said, if you are writing code that is in the getter or setter of a
property, you can still use the MethodInfo.GetCurrentMethod() method. The
name of the property is embedded in the names of the getter and setter
methods, since those names are just the name of the property with the text
"get_" and "set_" prepended.

If that doesn't provide what you want, I think you should try to rephrase
your question so that it's more clear.

Pete
Aug 17 '08 #2
On Aug 17, 9:23*am, Victor <Vic...@discussions.microsoft.comwrote:
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().Na me; 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
Aug 17 '08 #3
Actually, there is a way for instance properties using lambdas and
Expression (from .NET 3.5); I discussed it here:
http://groups.google.com/group/micro...05324df6b30218

What you have demonstrated are static properties; the same trick can
probably be made to apply - but in reality I doubt either is very
useful or convenient.

Marc
Aug 17 '08 #4

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

Aug 17 '08 #5
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/micro...05324df6b30218 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.

Aug 17 '08 #6
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
Aug 18 '08 #7
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
Aug 18 '08 #8
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;
}
}
"Marc Gravell" wrote:
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
Aug 18 '08 #9
I'm glad it was useful, then ;-p

Marc
Aug 18 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Sunny | last post by:
Hi, I have an old problem which I couldn't solve so far. Now I have found a post in that group that gave me an idea, but I can not fully understand it. The problem is: I'm trying to use a...
11
by: Simon Verona | last post by:
How can I write a line of code that sets an object to be an object thats contained on the parent form. Basically, I have a usercontrol, where one of the properties that I have added that can be...
0
by: davemc759 | last post by:
I have a complex Com object that I want to interrogate to discover the prperties of to allow me to save/restore it's state between instances. I have been able to accomplish this with the top level...
2
by: | last post by:
I'm writing web applications. I build and extend a lot of custom objects, and in the course of debugging my apps I invariably find myself writing a lot of junky code: Response.Write("Title: " +...
2
by: Luis Arvayo | last post by:
Hi, In c#, I need to dynamically create types at runtime that will consist of the following: - inherits from a given interface - will have a constructor with an int argument
5
by: heddy | last post by:
I understand that reflection allows me to discover the metadata of a class at runtime (properties, methods etc). What I don't understand is where this is useful. For example: If I am the sole...
9
by: Bill Grigg | last post by:
All, Can anyone supply an example or reference to an example of using reflection to determine the data types and array lengths contained in a nested stucture in C#? Actually, it is a structure...
6
by: Cralis | last post by:
Hi guys, Someone once said, 'You can do that with reflection'. I can't recall what it was I was trying to do at the time, but then he said, 'Any developer knows what reflection is...'. I kept...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.