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

Is this even possible?

public static string GetName(this object obj)
{
    return ... POOF! //should == "thing"
}
Benjamin
  • 3,134
  • 6
  • 36
  • 57
  • 2
    why would you want to do this? – BrokenGlass Dec 08 '11 at 02:39
  • As an extension method I doubt this would be easily possible. A method taking a `LambdaExpression` on the other hand would be able to do it. –  Dec 08 '11 at 02:43
  • @MatthewFerreira If the extension method version doesn't work and you could show me how to do it with a lambda expression I would be grateful. But maybe that should be a separate question? Thanks. – Benjamin Dec 08 '11 at 02:52
  • 1
    As far as I understand, local variables don't actually have a name once you compile code. The compiled code simply refers to variable 1, 2, 3... You can retrieve the name of method parameters and class members using reflection. – Hand-E-Food Dec 08 '11 at 02:57
  • @BrokenGlass I was just experimenting. With @Scott's anonymous type trick I can do `new {thing}.ThrowIfNull();`. I'm guessing it stinks for performance, but I think it is cool that I don't have to pass in any strings to use it in an error message. – Benjamin Dec 08 '11 at 19:24
  • I want to do this all the time in logging. – tigerswithguitars Jul 24 '19 at 13:07

4 Answers4

5

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.

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
  • This is great. Thank you. I'm still trying it out. I also found something online that looks similar http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html – Benjamin Dec 08 '11 at 14:51
  • 1
    @Benjamin That post was exactly what I was thinking! It even included info about using Lambda Expressions. It's like I plagiarized without even knowing it :) – Scott Rippey Dec 08 '11 at 20:55
  • 1
    Sadly the link is broken, I want to do this all the time for building good logging, `nameof()` has solved a lot of vandalism, but I want it to be fool (engineer) proof. – tigerswithguitars Jul 24 '19 at 13:09
4

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks. Is it because of compiling optimizations? – Benjamin Dec 08 '11 at 02:49
  • @Benjamin Well, the above will not work with optimizations, but there isn't a way, via reflection, to get details of the code. You can get method info and parameter info, but you'd need to get the variable passed into this method, and reflection doesn't provide that information... – Reed Copsey Dec 08 '11 at 02:50
  • @Benjamin It's not due to optimizations ... the names of local variables are never stored in compiled code (with or without optimizations), and therefore they're never available via reflection. Names of class members (properties, fields, methods, and parameters) ARE stored in the compiled code, and can therefore be accessed via reflection. – Scott Rippey Dec 08 '11 at 21:01
1

If you need the original variable name inside an extension method, I think it's best to do this:

thing.DoSomething(nameof(thing));

public static string DoSomething(this object obj, string name) {
    // name == "thing"
}
Rudey
  • 4,717
  • 4
  • 42
  • 84
-2

New in C# 6 is nameof() which would replace the extension method entirely.

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

Somewhat related is the CallerMemberAttribute which will get the name of the method where the function was called. A useful comparison of the two methods, with examples relating to PropertyChanged events, also talks about the IL code generated (TL;DR: they're the same).

drzaus
  • 24,171
  • 16
  • 142
  • 201
  • Anyone care to explain the problem? Random downvotes aren't helpful... – drzaus Oct 04 '16 at 20:21
  • You cannot get the original name of the first parameter in an extension method with `nameof`. Therefore, your answer does not answer the initial question. Please read the initial question once again and the accepted answer. – jfmg Oct 14 '16 at 16:02
  • @JFMG yes, but `nameof` **IS** the extension method the OP was attempting to write. I read the initial question and deduced what he was actually asking, which was "how do I get the name of a variable?" – drzaus Oct 14 '16 at 17:40
  • Well that is an interesting point of view. If you see it that way that he actually wanted to write an extension method to get the name of the variable, your answer would be right. Never thought about that. If you see it the way he asked, your answer is not relevant because with `nameof` you cannot get the original calling variable name inside your own extension method. – jfmg Oct 14 '16 at 21:08
  • @JFMG considering the timeframe when the question was originally asked, an extension method was probably the only/most convenient way the OP could think to get the variable's name. Since the question was already answered literally (=not possible) there would have been nothing for me to add. – drzaus Oct 18 '16 at 19:16
  • I suggest an edit. Something like: If you originally wanted to know the name of a variable with your extension method, then you can use `nameof`. – jfmg Oct 19 '16 at 09:04
  • 1
    I don't understand the downvotes. OP wants the name of a variable as a string, `nameof` does just that. It was never a requirement to get the original name inside an extension method. Extension methods was just OPs attempt to do the former. – Rudey Oct 03 '17 at 12:27