How to get the name of an object using reflection in .net?

In .net how to get the name of an object in a declaring type. For instance...

public static void Main() { Information dataInformation = new Information(); } public class Inforamtion { //Constructor public Inforamtion() { //Can I fetch name of object ie "dataInformation" declared in Main function //I want to set the object Name property = dataInformation here, because it is the name used in declaring that object. } public string Name = {get; set;} } 
+4
source share
3 answers

This is the name of the variable, not the name of the object. This also raises the question: what is called here:

 Information foo, bar; foo = bar = new Information(); 

You cannot do this for designers, etc .; in limited scenarios, you can get the variable name through Expression if you really want to:

  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 depends on the capture implementation, etc. and usually cheeky.

+3
source

As for the CLR, there is no way to determine the name of an object. Such information is stored (to some extent) in debugging and assembly information, but is not used at run time. Regardless, the object you are talking about is just a bunch of bytes in memory. It can have multiple references to it with multiple names, so even if you could get the names of all the variables that reference the object, it would be impossible to programmatically determine which one you want to use.

In short: you cannot do this.

+4
source

I do not think that's possible.

But first of all, why do you need something like this?

From my experience, I realized that if you need something strange from a compiler or a language that is not offered, then (most often) this means that something is wrong with the approach or logic.

Please change your mind about why you are trying to achieve this.

+1
source

All Articles