Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Is this even possible?

public static string GetName(this object obj)
{
    return ... POOF! //should == "thing"
}
like image 834
Benjamin Avatar asked Dec 08 '11 02:12

Benjamin


People also ask

What is this in extension method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is extension method with example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.

What are extension methods in LINQ?

Extension Methods are a new feature in C# 3.0, and they're simply user-made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modifying the original types.


2 Answers

I agree @Reed's answer. However, if you REALLY want to achieve this functionality, you could make this work:

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

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

The only other way would be to use a Lambda Expression, but the code would definitely be much more complicated.

like image 178
Scott Rippey Avatar answered Oct 29 '22 07:10

Scott Rippey


No. At the point you're using it, the "name" would be "obj" - This could be retrieved (with debugging symbols in place) via MethodBase.GetCurrentMethod().GetParameters()[0].Name.

However, you can't retrieve the variable name from the calling method.

like image 40
Reed Copsey Avatar answered Oct 29 '22 07:10

Reed Copsey