Short Answer: You can't.
Long Answer:
Technically, it's possible to determine a variable name by inspecting the IL (the intermidate language created by the C# compiler), but this operation is hard and error-prone. Also, you ignore some important questions:
First of all, as already asked here: Why? how such thing will enhance your program?
Each instance of the class can have multiple variables pointing to it (see my answer about types in .NET here). Which of them you want to get? For example, consider the following program:
var v1 = new TaskAction();
var c2 = new TaskAction();
c1.Increment(); // 1 c1
c2 = c1;
c2.Increment(); // 2 c1? 2 c2? 2 c1 c2?
- By doing so, you break the encapsulation in a difficult way - any reflection breaks the encapsulation, and really don't use it unless you really need it - but so much? Reflection breaks the hidden information about the private interface, you question breaks the internal interface!
Since you didn't give enough information, I can't know why you tought you need that. But here is some solutions:
If you want, for example, logging with categories - simply pass the category to the constructor, as sugegsted above.
If you want to know which type the variable is - using its name is very very very bad approach, even though you have conventions - use polymorphism instead (best), or, at least, check the type with is
/as
, for example:
if (this is Drived)
{
((Drived)this).SomeDrivedMethod();
}
Note that it breaks the OOP principles: a class shouldn't know about its drived classes.
Hope this helped you. Have a nice day!
Edit:
For your purpose, you can do one of the following:
Best - debug your code, see the call stack etc.
Worse - print the caller method name, instead of the object name. It's can be done using System.Runtime.CompilerServices.CallerMemberNameAttribute
:
void Increment([System.Runtime.CompilerServices.CallerMemberName] string caller = null)
{
// Default value to `caller` is neccessary
// ...
Console.WriteLine("Caller: {0}", caller);
}
Note: the compiler fills the caller
parameter, not in runtime.