Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get the name of a non-static property of a class

I have a question very similiar to another question: Get name of property as a string.

His solution ended up with

// Static Property 
string name = GetPropertyName(() => SomeClass.SomeProperty); 

// Instance Property 
string name = GetPropertyName(() => someObject.SomeProperty); 

What I'd like is to have syntax similar to the Static Property but for an instance property.

The reason is that I have code now that uses reflection to get the value of a property for all objects within a collection, but i have to pass that in as a hardcoded string.

Example code:

double Sum = AmountCollection.Sum("thatfield");  

Well, this works great, but if "thatfield" was ever renamed, the code would no longer work. The compiler cant check for that since it's just a string. Also, Get References won't work either for the same reason.

So, is there a way to achieve the goal of getting a property name easily, (ie; just a function call), from an instance property?

Thanks.

like image 769
David Avatar asked Oct 30 '25 23:10

David


1 Answers

Try this:

string name = GetPropertyName(() => default(SomeClass).SomeInstanceProperty);

You may get a compiler warning about "always causing a System.NullReferenceException", but that's not actually happening, since you don't execute the expression, which means that you can safely discard this warning. If you want to get rid of it, either disable it via pragma or just move the default() call into a function like this:

public static T Dummy<T>() {
  return default(T);
}

string name = GetPropertyName(() => Dummy<SomeClass>().SomeInstanceProperty);
like image 67
Lucero Avatar answered Nov 01 '25 12:11

Lucero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!