In .net how do I fetch object's name in the declaring type. For example...
public static void Main()
{
Information dataInformation = new Information();
}
public class Inforamtion
{
//Constructor
public Inforamtion()
{
//Can I fetch name of object i.e. "dataInformation" declared in Main function
//I want to set the object's Name property = dataInformation here, because it is the name used in declaring that object.
}
public string Name = {get; set;}
}
As far as the CLR goes, there's not really a way to determine an object's name. That sort of information is stored (to some extent) in the debugging information and the assembly, but it's not used at runtime. Regardless, the object you're referring to is just a bunch of bytes in memory. It could have multiple references to it with multiple names, so even if you could get the names of all the variables referencing the object, it would be impossible to programmatically determine which one you're looking to use.
Long story short: you can't do that.
That is the variable name, not the object name. It also poses the question: what is the name here:
Information foo, bar;
foo = bar = new Information();
You can't do this for constructors etc; in limited scenarios it is possible to get a variable name via Expression
, if you really want:
public static void Main()
{
Information dataInformation = new Information();
Write(() => dataInformation);
}
static void Write<T>(Expression<Func<T>> expression)
{
MemberExpression me = expression.Body as MemberExpression;
if (me == null) throw new NotSupportedException();
Console.WriteLine(me.Member.Name);
}
Note that this relies on the capture implementation, etc - and is generally cheeky.
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