Get the name of the first argument in the extension method?

string thing = "etc"; thing = thing.GetName(); //now thing == "thing" 

Is it possible?

 public static string GetName(this object obj) { return ... POOF! //should == "thing" } 
+6
source share
4 answers

Not. At the time you use it, the "name" will be "obj". This could be obtained (using debugging symbols in place) via MethodBase.GetCurrentMethod () GetParameters () [0] .Name.

However, you cannot get the variable name from the calling method.

+4
source

I agree to answer @Reed. However, if you really want to achieve this functionality, you can do this work:

 string thing = "etc"; thing = new{thing}.GetName(); 

The GetName extension method GetName simply use reflection to grab the name of the first property from an anonymous object.

The only other way is to use a Lambda expression, but the code will definitely be a lot more complicated.

+4
source

If you need the original variable name inside the extension method, I think the best thing to do is:

 thing.DoSomething(nameof(thing)); public static string DoSomething(this object obj, string name) { // name == "thing" } 
0
source

New in C # 6 nameof() , which would completely replace the extension method.

 if (x == null) throw new ArgumentNullException(nameof(x)); WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode" 

This is partly CallerMemberAttribute , which will get the name of the method in which the function was called. A useful comparison of the two methods with examples related to PropertyChanged events also suggests generating IL code (TL; DR: same).

-2
source

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


All Articles