Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle nameof(this) to report class name

Tags:

c#

c#-6.0

nameof

I'd like to use the following C#6 code

var joe = new Self();
Console.WriteLine(joe);

... and get the following output:

joe

The following attempt

class Self {
  public string Name { get; set; } = nameof(this);
  public override string ToString() {
    return Name;
  }
}

fails as nameof cannot be applied to this. Is it there a workaround for this problem?

EDIT. The scenario I'm working with assures that no two references point to the same Self object.

like image 368
nincsmail Avatar asked Jan 08 '15 10:01

nincsmail


People also ask

What does Nameof return in C#?

C# nameof operator returns the unqualified string name of a variable, type, or member.

What is the Nameof?

idiom. : used to indicate the name that is used for someone or something.

Is Nameof reflection?

Does it use Reflection? nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!

Is Nameof compile time C#?

Yes. nameof() is evaluated at compile-time.


2 Answers

No, nameof is designed to refer to the compile-time name of the member you're referring to. If you want an object to have a Name property as part of its state, that is independent of how you get to the Name property - as Frédéric Hamidi says, there could be multiple variables (or none) referring to the same object. Basically you need to differentiate between an object and a variable which happens to refer to that object.

However, if you have a constructor to specify the name, you could then use a couple of tricks to make it easier to get the right name:

class Self
{
    public string Name { get; }

    public Self([CallerMemberName] string name = null)
    {
        this.Name = name;
    }
}

Then:

class Foo
{
    private Self me = new Self(); // Equivalent to new Self("me")

    public void SomeMethod()
    {
        // Can't use the default here, as it would be "SomeMethod".
        // But we can use nameof...
        var joe = new Self(nameof(joe));
    }
}
like image 83
Jon Skeet Avatar answered Oct 21 '22 09:10

Jon Skeet


Maybe you can use the following method:

    class Self
    {
       public override string ToString()
       {
            return this.GetType().Name;
       }
    }
like image 10
Ivan Zalutskii Avatar answered Oct 21 '22 08:10

Ivan Zalutskii