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.
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));
}
}