0

I think the easiest way to explain my problem is with an example.

class MyClass
{
    string SomeFunction()
    {
          //magic 
    }
}

Void Main
{
    MyClass test = new MyClass();
    Console.WriteLine( SomeFunction );
}

So the thing I want “SomeFunktion” to is to give back the name of MyClass. In this case it would be “test”.

Is it even possible?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • possible but not efficient check this post http://stackoverflow.com/questions/2566101/how-to-get-variable-name-using-reflection – Krazibit312 May 03 '15 at 04:52

1 Answers1

4

BTW it should be Console.WriteLine(test.SomeFunction());

and

No you cannot do that unless you are using C# 6.

In C# 6, you have an operator nameof where you can pass instance and it returns name of instance like in your case "test" like nameof(test) and it would return "test".

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • But no...nameof can't know the name of the variable that refers to the instance on which the method is called. Suppose two variables pointed to the same object? What then? – phoog May 03 '15 at 04:42
  • nameof has nothing to do with reference. Read here https://msdn.microsoft.com/en-us/magazine/dn802602.aspx – Nikhil Agrawal May 03 '15 at 04:43
  • 1
    I know what nameof does. The question is asking whether an instance method of MyClass can get the name of the "test" variable in the calling method, and the answer is no. Your solution allows the calling method to get the name of its own variable, which is as close as you can get, but it does not actually solve the problem as posed by the OP (because, as you say, nameof has nothing to do with reference). – phoog May 03 '15 at 04:53