losingsleeep
losingsleeep

Reputation: 1879

how to get full name of an object in .NET?

In .NET (originally .NET CF), how to get full address and name of an object?

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            Button myButton = new Button();
            MessageBox.Show(GetFullName(myButton));
        }

        string GetFullName(object obj)
        {
            string path = null;
            // should retrieve the 'WindowsFormsApplication1.Form2.myButton' , but how?
            return path;
        }

    }
}

Upvotes: 2

Views: 758

Answers (2)

Anders Abel
Anders Abel

Reputation: 69260

// should retrieve the 'WindowsFormsApplication1.Form2.myButton' , but how?

That's not possible.

An object in C# resides somewhere on the managed heap (it can even be moved around) and is identified by a reference to it. There can be many references to the same object, but there is no "back pointer" from the object to everywhere it is referenced.

class Program
{
  int number;
  public Program next;

  private static Program p1 { number = 1 };
  private static Program p2 { number = 2, next = p1 }

  private static int Main(int argc, string[] argv)
  {
    p2.DoStuff(p2);
  }

  void DoStuff(Program p)
  {
    // In here, the program with m_Number = 1 can be reached
    // as p1, p.next, p2.next and this.next. All of them are
    // references to the same object.
  }
}

Upvotes: 2

Brian
Brian

Reputation: 38025

Like others have said, myButton is a variable in your example so it doesn't have a name like a member of a class normally would. However, you can try something like this (notice I set the Name property on the button and changed the parameter to a Control)...

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            Button myButton = new Button();
            myButton.Name = "myButton";
            MessageBox.Show(GetFullName(myButton));
        }

        string GetFullName(Control ctl)
        {
            return string.Format("{0}.{1}", this.GetType().FullName, ctl.Name);
        }

    }
}

Upvotes: 2

Related Questions