Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch object name using reflection in .net?

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;}
}
like image 755
Software Enthusiastic Avatar asked Feb 28 '23 03:02

Software Enthusiastic


2 Answers

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.

like image 169
Adam Maras Avatar answered Mar 02 '23 20:03

Adam Maras


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.

like image 23
Marc Gravell Avatar answered Mar 02 '23 18:03

Marc Gravell