Hi Pete:
I can think of a particular time when it would be kind of nice to get that
type of information. For example, given the function below:
public void MyFunction(int someArg)
{
If (someArg == 0)
throw new ArgumentException(“someArg cant be equal to zeroâ€);
}
What would happen if I changed the name of “someArg†to something else like
“myArg� If I do that then I would have to make sure I update the Exception
description too.
I don’t want to be critical about this but it would be nice if there was a
compiler method like “GetIdentifierName()†that could be used so that when
you throw the error you can do something like the following:
throw new ArgumentException( GetIdentifierName(someArg) + “cant be equal to
zeroâ€);
This way, if I was to change the name of the argument to “myArg†I would get
a compile error but chances are that will never happen because most people
would refactor the code and everything would be take care of automatically.
Cheers.
Is there a way for an object to know the identifier which has called it
MyClass myClassObjectId = new MyClass();
how can I get the name of the identifier "myClassObjectId" which is
calling
the object from within the object itself. ??
public string IdName { get{ return ?????? } }
The only way that I can think of would be to use reflection to inspect the
call stack, then the line of code making the call, to extract the variable
(be it a local or class field) referencing the instance on which the
method was called.
But surely the likelihood of this being a correct design is extremely low.
What exactly are you trying to accomplish? We know the implementation you
have in mind, but what actual problem are you trying to solve? It seems
doubtful that learning the identifier of the variable referencing the
instance used to call some particular instance code is really a good thing
to be doing, generally.
Pete