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.
C# nameof operator returns the unqualified string name of a variable, type, or member.
idiom. : used to indicate the name that is used for someone or something.
Does it use Reflection? nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!
Yes. nameof() is evaluated at compile-time.
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));
}
}
Maybe you can use the following method:
class Self
{
public override string ToString()
{
return this.GetType().Name;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With