Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How can I get the name of the object from Reflection ?

How can I get the name of the object from Reflection ?

Scheduled Pinned Locked Moved C#
tutorialquestion
14 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    Nadia Monalisa
    wrote on last edited by
    #1

    Hello, I need to get the name of the Object using Reflection, but I am getting all information about how to get the name of the Type using Reflection rather than the Object. For example, I got the following code,

    public class Demo
    {
    public int ID { get; set; }
    public string Name { get; set; }
    }

    private void button1_Click(object sender, EventArgs e)
    {
    Demo myDemo = new Demo {ID = 10, Name = "Kab"};

    var theType = myDemo.ID.GetType();
    MessageBox.Show(theType.Name);
    

    }

    When I click the button1, The message box shows "Int32", but I need to see "ID". Would you please tell me how I can achieve this goal! Regards.

    L P D C 4 Replies Last reply
    0
    • N Nadia Monalisa

      Hello, I need to get the name of the Object using Reflection, but I am getting all information about how to get the name of the Type using Reflection rather than the Object. For example, I got the following code,

      public class Demo
      {
      public int ID { get; set; }
      public string Name { get; set; }
      }

      private void button1_Click(object sender, EventArgs e)
      {
      Demo myDemo = new Demo {ID = 10, Name = "Kab"};

      var theType = myDemo.ID.GetType();
      MessageBox.Show(theType.Name);
      

      }

      When I click the button1, The message box shows "Int32", but I need to see "ID". Would you please tell me how I can achieve this goal! Regards.

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      The Type object for the ID field has no knowledge of the Demo class. If you want to get the name "ID" you will have to do it through the type object of Demo, and get a FieldInfo of the field ID. The property Name of that FieldInfo object will hold the string "ID". That does not sound very useful to me though, because you already had to know that the field is called ID to find it in the first place.

      N 1 Reply Last reply
      0
      • L Lost User

        The Type object for the ID field has no knowledge of the Demo class. If you want to get the name "ID" you will have to do it through the type object of Demo, and get a FieldInfo of the field ID. The property Name of that FieldInfo object will hold the string "ID". That does not sound very useful to me though, because you already had to know that the field is called ID to find it in the first place.

        N Offline
        N Offline
        Nadia Monalisa
        wrote on last edited by
        #3

        Hi Harold, Thanks a lot, so sounds like, I will have to use a method within a FieldInfo where the passing argument will be the name of the field "ID" in this case, right ? If so, then, yes, this solution is not useful, because as you said, I will have to know the name "ID" before I can get it from FieldInfo. Is not there any other solution which can give me the result "ID" from the passing object without passing the string "ID" ?

        L 1 Reply Last reply
        0
        • N Nadia Monalisa

          Hello, I need to get the name of the Object using Reflection, but I am getting all information about how to get the name of the Type using Reflection rather than the Object. For example, I got the following code,

          public class Demo
          {
          public int ID { get; set; }
          public string Name { get; set; }
          }

          private void button1_Click(object sender, EventArgs e)
          {
          Demo myDemo = new Demo {ID = 10, Name = "Kab"};

          var theType = myDemo.ID.GetType();
          MessageBox.Show(theType.Name);
          

          }

          When I click the button1, The message box shows "Int32", but I need to see "ID". Would you please tell me how I can achieve this goal! Regards.

          P Offline
          P Offline
          PIEBALDconsult
          wrote on last edited by
          #4

          Basically you can't. You could override the ToString method of Demo to return "ID" though.

          N 1 Reply Last reply
          0
          • N Nadia Monalisa

            Hi Harold, Thanks a lot, so sounds like, I will have to use a method within a FieldInfo where the passing argument will be the name of the field "ID" in this case, right ? If so, then, yes, this solution is not useful, because as you said, I will have to know the name "ID" before I can get it from FieldInfo. Is not there any other solution which can give me the result "ID" from the passing object without passing the string "ID" ?

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            There can be, will ID be the only field? Or will there be some other distinguishing feature about it, such as ID being the only field of type Int32?

            N 1 Reply Last reply
            0
            • L Lost User

              There can be, will ID be the only field? Or will there be some other distinguishing feature about it, such as ID being the only field of type Int32?

              N Offline
              N Offline
              Nadia Monalisa
              wrote on last edited by
              #6

              Hi Harold, Thanks for the reply again. No, there could be more integers in the Demo class. But I want to pass the object to a method where the method needs to extract the name of this object "ID" in this case from reflection without asking any more information. So, sounds like, I cannot do that with .NET 4. Anyway, thanks a lot for your suggessions.

              L 1 Reply Last reply
              0
              • P PIEBALDconsult

                Basically you can't. You could override the ToString method of Demo to return "ID" though.

                N Offline
                N Offline
                Nadia Monalisa
                wrote on last edited by
                #7

                Hi, Yes, thats what I see, I can't get this information. I hope future version of .NET will allow us to do that.

                P 1 Reply Last reply
                0
                • N Nadia Monalisa

                  Hi Harold, Thanks for the reply again. No, there could be more integers in the Demo class. But I want to pass the object to a method where the method needs to extract the name of this object "ID" in this case from reflection without asking any more information. So, sounds like, I cannot do that with .NET 4. Anyway, thanks a lot for your suggessions.

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  I don't think you could do it at all, not even theoretically, how would you know which field to choose? Would a custom attribute to mark it be an option?

                  N 1 Reply Last reply
                  0
                  • L Lost User

                    I don't think you could do it at all, not even theoretically, how would you know which field to choose? Would a custom attribute to mark it be an option?

                    N Offline
                    N Offline
                    Nadia Monalisa
                    wrote on last edited by
                    #9

                    Hi Harold, No, the object is actually a LINQ to SQL Model, so I cannot add custom attribute (unless I dont want to re build the LINQ to SQL Classes by Visual Studio). So, I give up :) Thanks again.

                    L 1 Reply Last reply
                    0
                    • N Nadia Monalisa

                      Hello, I need to get the name of the Object using Reflection, but I am getting all information about how to get the name of the Type using Reflection rather than the Object. For example, I got the following code,

                      public class Demo
                      {
                      public int ID { get; set; }
                      public string Name { get; set; }
                      }

                      private void button1_Click(object sender, EventArgs e)
                      {
                      Demo myDemo = new Demo {ID = 10, Name = "Kab"};

                      var theType = myDemo.ID.GetType();
                      MessageBox.Show(theType.Name);
                      

                      }

                      When I click the button1, The message box shows "Int32", but I need to see "ID". Would you please tell me how I can achieve this goal! Regards.

                      D Offline
                      D Offline
                      ddecoy
                      wrote on last edited by
                      #10

                      And what about this:

                      Demo demo = new Demo();
                      demo.ID = 1;
                      demo.Name = "Demo";
                      foreach ( Fi in demo.GetType.GetFields(BindingFlags.Public | BindingFlags.Instance)) {
                      Console.WriteLine("--" + Fi.Name);
                      }

                      gives you "ID" and "Name".

                      D 1 Reply Last reply
                      0
                      • D ddecoy

                        And what about this:

                        Demo demo = new Demo();
                        demo.ID = 1;
                        demo.Name = "Demo";
                        foreach ( Fi in demo.GetType.GetFields(BindingFlags.Public | BindingFlags.Instance)) {
                        Console.WriteLine("--" + Fi.Name);
                        }

                        gives you "ID" and "Name".

                        D Offline
                        D Offline
                        ddecoy
                        wrote on last edited by
                        #11

                        And to get the value for ID and Name :

                        Fi.GetValue(demo);

                        1 Reply Last reply
                        0
                        • N Nadia Monalisa

                          Hi Harold, No, the object is actually a LINQ to SQL Model, so I cannot add custom attribute (unless I dont want to re build the LINQ to SQL Classes by Visual Studio). So, I give up :) Thanks again.

                          L Offline
                          L Offline
                          Lukasz Nowakowski
                          wrote on last edited by
                          #12

                          If this field is primary key and you're using LINQ to SQL, then check ColumnAttribute (you can view it by opening source file generated by LINQ to SQL engine). There's a property IsPrimaryKey, which may be useful to you.

                          Don't forget to rate answer, that helped you. It will allow other people find their answers faster.

                          1 Reply Last reply
                          0
                          • N Nadia Monalisa

                            Hi, Yes, thats what I see, I can't get this information. I hope future version of .NET will allow us to do that.

                            P Offline
                            P Offline
                            PIEBALDconsult
                            wrote on last edited by
                            #13

                            You can hope all you want; it ain't gonna happen.

                            1 Reply Last reply
                            0
                            • N Nadia Monalisa

                              Hello, I need to get the name of the Object using Reflection, but I am getting all information about how to get the name of the Type using Reflection rather than the Object. For example, I got the following code,

                              public class Demo
                              {
                              public int ID { get; set; }
                              public string Name { get; set; }
                              }

                              private void button1_Click(object sender, EventArgs e)
                              {
                              Demo myDemo = new Demo {ID = 10, Name = "Kab"};

                              var theType = myDemo.ID.GetType();
                              MessageBox.Show(theType.Name);
                              

                              }

                              When I click the button1, The message box shows "Int32", but I need to see "ID". Would you please tell me how I can achieve this goal! Regards.

                              C Offline
                              C Offline
                              Chris Trelawny Ross
                              wrote on last edited by
                              #14

                              You need to use Linq Expression objects to get the name of a property, from the property itself. Here's a simple test program that demonstrates what you have to do:

                              using System;
                              using System.Collections.Generic;
                              using System.Linq;
                              using System.Text;
                              using System.ComponentModel;
                              using System.Linq.Expressions;
                              using System.Reflection;

                              namespace ConsoleApplication4
                              {
                              class Program
                              {
                              static void Main(string[] args)
                              {
                              Consumer c = new Consumer();
                              c.TestIt();
                              }
                              }

                              public class Demo
                              {
                              public int InstanceProperty { get; set; }
                              public string InstanceField;
                              static public int TypeField;
                              static public int TypeProperty { get; set; }
                              }

                              public class Consumer
                              {
                              public void TestIt()
                              {
                              button1_click(this, new EventArgs());
                              }

                              private void button1\_click(object sender, EventArgs e)
                              	{
                              	Demo myDemo = new Demo { InstanceProperty = 10, InstanceField = "Kab" };
                              	string n1 = GetMemberName(() => myDemo.InstanceField);
                              	string n2 = GetMemberName(() => myDemo.InstanceProperty);
                              	string n3 = GetMemberName(() => Demo.TypeField);
                              	string n4 = GetMemberName(() => Demo.TypeProperty);
                              	string n5 = GetMemberName(() => myDemo);	// This was a surprise - I expected it to fail!
                              	}
                              
                              private string GetMemberName<T>(Expression<Func<T>> itemSpecifierExpression)
                              	{
                              	var bodyAsMemberExpression = itemSpecifierExpression.Body as MemberExpression;
                              	if (bodyAsMemberExpression == null)
                              		throw new ArgumentException("itemSpecifierExpression does not specify an object or an instance or type member");
                              	var propInfo = bodyAsMemberExpression.Member as MemberInfo;
                              	return bodyAsMemberExpression.Member.Name; 
                              	}
                              
                              }
                              

                              }

                              Note - it may be possible to simplify things a bit, but I've not used Expression enough to be sure. See INotifyPropertyChanging[^] by atverma[^] for the article where I first saw the technique used.

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups