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

I have a question very similar to another question: Get the property name as a string .

His decision is over

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

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

I would like to have syntax similar to Static Property, but for instance property.

The reason is that now I have code that uses reflection to get the property value for all objects within the collection, but I have to pass this as a hard-coded string.

Code example:

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

Ok, this works great, but if "thisfield" is ever renamed, the code will no longer work. The compiler cannot verify this, because it is just a string. In addition, Get References will not work for the same reason.

, (.. ) ?

.

+3
2

:

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

" System.NullReferenceException", , , , . , default() , :

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

string name = GetPropertyName(() => Dummy<SomeClass>().SomeInstanceProperty);
+5

# 6.0 nameof:

 nameof(SomeProperty)

"SomeProperty".

0
source

Source: https://habr.com/ru/post/1751895/


All Articles