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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Reflection: Getting property name from property itself

Reflection: Getting property name from property itself

Scheduled Pinned Locked Moved C#
csshelp
17 Posts 8 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.
  • E Ennis Ray Lynch Jr

    someOjbect.GetType().GetProperties() will give you the collection of all properties in an object. You will be able to use .Name on a propertyInfo object to get the name.

    Need a C# Consultant? I'm available.
    Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway

    G Offline
    G Offline
    GazzaJ
    wrote on last edited by
    #5

    If I get a list of properties using GetProperties() how do I get the propertyInfo of the property I'm interested in without specifying a string to identify it.

    P 1 Reply Last reply
    0
    • G GazzaJ

      I am configuring a grid and pass in the name of the property within an object to display e.g. myGrid.AddColumn(new ColumnDefn("TestPropertyName", "", false, true)); where TestPropertyName is the property within the object to display. Instead of using a string to identify the property I want to use the object itself e.g. MyObject myObject = new MyObject(); myGrid.AddColumn(new ColumnDefn(myObject.TestPropertyName.xxxxx, "", false, true)); where xxx is some magic to get the property name (I assume using reflection). This means if myObject changes (e.g. TestPropertyName becomes TestPropertyName2) I will pick up the error at compile time.

      J Offline
      J Offline
      Judah Gabriel Himango
      wrote on last edited by
      #6

      You can do this using lambda expressions in C# 3. See http://themechanicalbride.blogspot.com/2007/03/symbols-on-steroids-in-c.html[^] for more info.

      using System.Linq.Expressions;
      public static class SymbolExtensions
      {
          public static string GetPropertySymbol<T, R>(this T target, Expression<Func<T, R>> expression)
          {
              return ((MemberExpression)(((LambdaExpression)(expression)).Body)).Member.Name;
          }
      }

      You can then call it like this:

      string propertyName = myObject.GetPropertySymbol(o => o.MyTestProperty);
      myGrid.AddColumn(new ColumnDefn(propertyName, "", false, true));

      Using this technique, you can get the name of a property or method without using strings at all. This can be beneficial in unit testing, INotifyPropertyChanged implementations, and other scenarios where hard-coding a string is a bad option.

      Tech, life, family, faith: Give me a visit. I'm currently blogging about: What this world needs... (Video) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

      G S 2 Replies Last reply
      0
      • J Judah Gabriel Himango

        You can do this using lambda expressions in C# 3. See http://themechanicalbride.blogspot.com/2007/03/symbols-on-steroids-in-c.html[^] for more info.

        using System.Linq.Expressions;
        public static class SymbolExtensions
        {
            public static string GetPropertySymbol<T, R>(this T target, Expression<Func<T, R>> expression)
            {
                return ((MemberExpression)(((LambdaExpression)(expression)).Body)).Member.Name;
            }
        }

        You can then call it like this:

        string propertyName = myObject.GetPropertySymbol(o => o.MyTestProperty);
        myGrid.AddColumn(new ColumnDefn(propertyName, "", false, true));

        Using this technique, you can get the name of a property or method without using strings at all. This can be beneficial in unit testing, INotifyPropertyChanged implementations, and other scenarios where hard-coding a string is a bad option.

        Tech, life, family, faith: Give me a visit. I'm currently blogging about: What this world needs... (Video) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

        G Offline
        G Offline
        GazzaJ
        wrote on last edited by
        #7

        That looks like what I want but I am stuck on .NET v2!

        J 1 Reply Last reply
        0
        • G GazzaJ

          That looks like what I want but I am stuck on .NET v2!

          J Offline
          J Offline
          Judah Gabriel Himango
          wrote on last edited by
          #8

          Stuck in 2.0 land, eh? The one possible way to do this without a string is from within the property or method itself:

          string nameOfTheProperty;
          ...

          public string MyProperty
          {
             get
             {
                 nameOfTheProperty = MethodInfo.GetCurrentMethod().Name;
             }
          }

          This has the obvious downside of having to invoke the property in order to get its name. Another possibility that works only with methods (it doesn't work with properties) is by using delegates:

          MethodInvoker dummyDelegate = MyFunction;
          string nameOfTheMethod = dummyDelegate.Method.Name;

          ...

          void MyFunction()
          {
          }

          Tech, life, family, faith: Give me a visit. I'm currently blogging about: What this world needs... (Video) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

          D 1 Reply Last reply
          0
          • J Judah Gabriel Himango

            You can do this using lambda expressions in C# 3. See http://themechanicalbride.blogspot.com/2007/03/symbols-on-steroids-in-c.html[^] for more info.

            using System.Linq.Expressions;
            public static class SymbolExtensions
            {
                public static string GetPropertySymbol<T, R>(this T target, Expression<Func<T, R>> expression)
                {
                    return ((MemberExpression)(((LambdaExpression)(expression)).Body)).Member.Name;
                }
            }

            You can then call it like this:

            string propertyName = myObject.GetPropertySymbol(o => o.MyTestProperty);
            myGrid.AddColumn(new ColumnDefn(propertyName, "", false, true));

            Using this technique, you can get the name of a property or method without using strings at all. This can be beneficial in unit testing, INotifyPropertyChanged implementations, and other scenarios where hard-coding a string is a bad option.

            Tech, life, family, faith: Give me a visit. I'm currently blogging about: What this world needs... (Video) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

            S Offline
            S Offline
            S Senthil Kumar
            wrote on last edited by
            #9

            Thanks for the link. That was a really neat trick, must be the most creative use of ExpressionTrees I've found so far (besides their intended purpose).

            Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

            1 Reply Last reply
            0
            • J Judah Gabriel Himango

              Stuck in 2.0 land, eh? The one possible way to do this without a string is from within the property or method itself:

              string nameOfTheProperty;
              ...

              public string MyProperty
              {
                 get
                 {
                     nameOfTheProperty = MethodInfo.GetCurrentMethod().Name;
                 }
              }

              This has the obvious downside of having to invoke the property in order to get its name. Another possibility that works only with methods (it doesn't work with properties) is by using delegates:

              MethodInvoker dummyDelegate = MyFunction;
              string nameOfTheMethod = dummyDelegate.Method.Name;

              ...

              void MyFunction()
              {
              }

              Tech, life, family, faith: Give me a visit. I'm currently blogging about: What this world needs... (Video) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

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

              Judah Himango wrote:

              Another possibility that works only with methods (it doesn't work with properties) is by using delegates

              I thought I had an idea but "cannot explicitly call operator or accessor" Damn.


              [My Blog]
              "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
              "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

              1 Reply Last reply
              0
              • G GazzaJ

                If I get a list of properties using GetProperties() how do I get the propertyInfo of the property I'm interested in without specifying a string to identify it.

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

                GetProperties() returns the PropertyInfo

                1 Reply Last reply
                0
                • G GazzaJ

                  I am configuring a grid and pass in the name of the property within an object to display e.g. myGrid.AddColumn(new ColumnDefn("TestPropertyName", "", false, true)); where TestPropertyName is the property within the object to display. Instead of using a string to identify the property I want to use the object itself e.g. MyObject myObject = new MyObject(); myGrid.AddColumn(new ColumnDefn(myObject.TestPropertyName.xxxxx, "", false, true)); where xxx is some magic to get the property name (I assume using reflection). This means if myObject changes (e.g. TestPropertyName becomes TestPropertyName2) I will pick up the error at compile time.

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

                  Don't send in the name of the property, send in the PropertyInfo instead. typeof(myObject).GetProperty("TestPropertyName")

                  namespace Template
                  {
                  public class X
                  {
                  public string
                  Name
                  {
                  get
                  {
                  return ( "Malcolm" ) ;
                  }
                  }
                  }

                  public partial class Template
                  {
                      private static void
                      DisplayPropertyNameAndType
                      (
                          **System.Reflection.PropertyInfo Prop**
                      )
                      {
                          System.Console.WriteLine
                          (
                              "{0} is {1}"
                          ,
                              **Prop.Name**
                          ,
                              **Prop.PropertyType**
                          ) ;
                  
                          return ;
                      }
                  
                      \[System.STAThreadAttribute()\]
                      public static int
                      Main
                      (
                          string\[\] args
                      )
                      {
                          int result = 0 ;
                  
                          try
                          {
                              DisplayPropertyNameAndType ( **typeof(X).GetProperty ( "Name" )** ) ;
                          }
                          catch ( System.Exception err )
                          {
                              System.Console.Write ( err.Message ) ;
                          }
                  
                          return ( result ) ;
                      }
                  }
                  

                  }

                  The PropertyInfo can also provide the type to which it belongs: .ReflectedType

                  modified on Monday, January 14, 2008 3:05:00 PM

                  G 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    Don't send in the name of the property, send in the PropertyInfo instead. typeof(myObject).GetProperty("TestPropertyName")

                    namespace Template
                    {
                    public class X
                    {
                    public string
                    Name
                    {
                    get
                    {
                    return ( "Malcolm" ) ;
                    }
                    }
                    }

                    public partial class Template
                    {
                        private static void
                        DisplayPropertyNameAndType
                        (
                            **System.Reflection.PropertyInfo Prop**
                        )
                        {
                            System.Console.WriteLine
                            (
                                "{0} is {1}"
                            ,
                                **Prop.Name**
                            ,
                                **Prop.PropertyType**
                            ) ;
                    
                            return ;
                        }
                    
                        \[System.STAThreadAttribute()\]
                        public static int
                        Main
                        (
                            string\[\] args
                        )
                        {
                            int result = 0 ;
                    
                            try
                            {
                                DisplayPropertyNameAndType ( **typeof(X).GetProperty ( "Name" )** ) ;
                            }
                            catch ( System.Exception err )
                            {
                                System.Console.Write ( err.Message ) ;
                            }
                    
                            return ( result ) ;
                        }
                    }
                    

                    }

                    The PropertyInfo can also provide the type to which it belongs: .ReflectedType

                    modified on Monday, January 14, 2008 3:05:00 PM

                    G Offline
                    G Offline
                    GazzaJ
                    wrote on last edited by
                    #13

                    Thanks for all the help. I'm still not sure this is what I want. I don't want any hardcoded literal strings. In the code above I still have to use the string "Name" to get the information. I have an object myObject which has a property TestProperty ie myObject.TestProperty. Using only this I want to get a string of the property name e.g. SomeCode(myObject.TestProperty) returns "TestProperty"

                    D P 2 Replies Last reply
                    0
                    • G GazzaJ

                      Thanks for all the help. I'm still not sure this is what I want. I don't want any hardcoded literal strings. In the code above I still have to use the string "Name" to get the information. I have an object myObject which has a property TestProperty ie myObject.TestProperty. Using only this I want to get a string of the property name e.g. SomeCode(myObject.TestProperty) returns "TestProperty"

                      D Offline
                      D Offline
                      DaveyM69
                      wrote on last edited by
                      #14

                      Have a look at the thread that this[^] message is in. Ed helped me enormously doing remarkable stuff with properties/reflection and more here - it might get you going in the direction you're looking for.

                      1 Reply Last reply
                      0
                      • G GazzaJ

                        Thanks for all the help. I'm still not sure this is what I want. I don't want any hardcoded literal strings. In the code above I still have to use the string "Name" to get the information. I have an object myObject which has a property TestProperty ie myObject.TestProperty. Using only this I want to get a string of the property name e.g. SomeCode(myObject.TestProperty) returns "TestProperty"

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

                        myObject.TestProperty results in only the value of the instance's property. myObject.GetType().GetProperty("TestProperty") should get you the property, but lose the instance. I think I need to go back and read this thread from the beginning again to see what I may have missed.

                        1 Reply Last reply
                        0
                        • G GazzaJ

                          I am configuring a grid and pass in the name of the property within an object to display e.g. myGrid.AddColumn(new ColumnDefn("TestPropertyName", "", false, true)); where TestPropertyName is the property within the object to display. Instead of using a string to identify the property I want to use the object itself e.g. MyObject myObject = new MyObject(); myGrid.AddColumn(new ColumnDefn(myObject.TestPropertyName.xxxxx, "", false, true)); where xxx is some magic to get the property name (I assume using reflection). This means if myObject changes (e.g. TestPropertyName becomes TestPropertyName2) I will pick up the error at compile time.

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

                          Yeah I still don't think it can be done without either myval.GetType().GetProperty("Name") or typeof(mytyp).GetProperty("Name") But, consider this... Write a custom Attribute and use it to decorate fields in the classes you want to use with your grid (assuming you only want to support classes you write). Then just pass the new type into your grid.

                          public class GridAttribute : Attribute {}

                          public class MyClass
                          {
                          [GridAttribute()]
                          public int SomeProperty ...
                          }

                          Grid grid = new Grid(typeof(MyClass)) ;
                          --or, better--
                          Grid grid = new Grid<myclass>() ; -- Fixed brackets

                          Then in the constructor for Grid: enumerate the fields of typeof(T) (MyClass) , enumerate the CustomAttributes of each, add each that has the attribute. P.S. This past week I was playing with passing an enum into a generic class that will investigate its fields looking for a CustomAttribute.

                          1 Reply Last reply
                          0
                          • G GazzaJ

                            I am configuring a grid and pass in the name of the property within an object to display e.g. myGrid.AddColumn(new ColumnDefn("TestPropertyName", "", false, true)); where TestPropertyName is the property within the object to display. Instead of using a string to identify the property I want to use the object itself e.g. MyObject myObject = new MyObject(); myGrid.AddColumn(new ColumnDefn(myObject.TestPropertyName.xxxxx, "", false, true)); where xxx is some magic to get the property name (I assume using reflection). This means if myObject changes (e.g. TestPropertyName becomes TestPropertyName2) I will pick up the error at compile time.

                            N Offline
                            N Offline
                            NassosReyzidis
                            wrote on last edited by
                            #17

                            Hi there, I have an idea that i saw first in the WPF implementation, you can put some public static const variables in your object implementation so that you can call the appropriate property: public class MyObject { public static const string refTestPropertyName = "TestPropertyName"; private string _TestPropertyName; public string TestPropertyName { get{return _TestPropertyName;} set{_TestPropertyName=value;} } .... } now in your code: MyObject myObject = new MyObject(); myGrid.AddColumn(new ColumnDefn(myObject.refTestPropertyName , "", false, true)); Hope that helped Nassos

                            "Success is the ability to go from one failure to another with no loss of enthusiasm." Winston Churchill "Quality means doing it right when no one is looking." Henry Ford

                            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