C
C#2y ago
Binto86

✅ Get instance name inside of class

So i have class like this:
private class CliFlag
{
public object Value { get; }
public CliFlag(object value)
{
this.Value = value;
}
}
private class CliFlag
{
public object Value { get; }
public CliFlag(object value)
{
this.Value = value;
}
}
and i want to create ToString that will return -[nameOfTheCliFlag] [valueOfTheFlag] like this
var flag = new CliFlag("x");
flag.ToString(); // -flag x
var flag = new CliFlag("x");
flag.ToString(); // -flag x
however i can't find o way to get the name of the current instance inside of the class, i thought about nameof(this), but that doesn't work is there any way how to get this working without passing the name of the flag from outside?
5 Replies
canton7
canton72y ago
That's not even the name of the current instance. That's the name of the variable to which the current instance is assigned
Binto86
Binto86OP2y ago
fair
canton7
canton72y ago
And no, there's no way to find that. Your instance might not even be assigned to a variable: it might be stored in a list, or simply be an expression. Also variable names are lost at compile time
Binto86
Binto86OP2y ago
ok, i guess that makes sense, thanks for help, i will try different approach here
Anton
Anton2y ago
store the name alongside the value
Want results from more Discord servers?
Add your server