Reflection: How to discover name of a property at run time.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?VmljdG9y?=

    Reflection: How to discover name of a property at run time.

    Is it a way to discover, at the run time, the name of a property of an object?
    In other words is it possible to create a method GetPropertyName , that takes
    a property of an object and returns the name of that property? So:

    string name = GetPropertyName (int.MaxValue); // returns “MaxValue”
    string name = GetPropertyName (DateTime.Now); // returns “Now”

    (Something similar exists to
    System.Reflecti on.MethodInfo.G etCurrentMethod ().Name; that returns the name
    of the current method)

  • Peter Duniho

    #2
    Re: Reflection: How to discover name of a property at run time.

    On Sat, 16 Aug 2008 21:23:00 -0700, Victor
    <Victor@discuss ions.microsoft. comwrote:
    Is it a way to discover, at the run time, the name of a property of an
    object?
    In other words is it possible to create a method GetPropertyName , that
    takes
    a property of an object and returns the name of that property? So:
    >
    string name = GetPropertyName (int.MaxValue); // returns “MaxValue”
    string name = GetPropertyName (DateTime.Now); // returns “Now”
    >
    (Something similar exists to
    System.Reflecti on.MethodInfo.G etCurrentMethod ().Name; that returns the
    name
    of the current method)
    MethodInfo.GetC urrentMethod() is only useful when called from _within_ the
    method in question. That's completely different from the example lines of
    code you posted, so it's very difficult to understand exactly what you
    want to do.

    That said, if you are writing code that is in the getter or setter of a
    property, you can still use the MethodInfo.GetC urrentMethod() method. The
    name of the property is embedded in the names of the getter and setter
    methods, since those names are just the name of the property with the text
    "get_" and "set_" prepended.

    If that doesn't provide what you want, I think you should try to rephrase
    your question so that it's more clear.

    Pete

    Comment

    • Duggi

      #3
      Re: Reflection: How to discover name of a property at run time.

      On Aug 17, 9:23 am, Victor <Vic...@discuss ions.microsoft. comwrote:
      Is it a way to discover, at the run time, the name of a property of an object?
      In other words is it possible to create a method GetPropertyName , that takes
      a property of an object and returns the name of that property? So:
      >
      string name = GetPropertyName (int.MaxValue); // returns “MaxValue”
      string name = GetPropertyName (DateTime.Now); // returns “Now”
      >
      (Something similar exists to
      System.Reflecti on.MethodInfo.G etCurrentMethod ().Name; that returns the name
      of the current method)

      Try the following snippet of code..

      Type myType = tc.GetType();
      PropertyInfo[] allPropertiesIn fo = myType.GetPrope rties();

      foreach (PropertyInfo pInfo in allPropertiesIn fo)
      {
      Console.WriteLi ne(((System.Ref lection.MemberI nfo)(pInfo)).Na me);
      }

      Hope this would be useful.

      -Cnu

      Comment

      • Marc Gravell

        #4
        Re: Reflection: How to discover name of a property at run time.

        Actually, there is a way for instance properties using lambdas and
        Expression (from .NET 3.5); I discussed it here:


        What you have demonstrated are static properties; the same trick can
        probably be made to apply - but in reality I doubt either is very
        useful or convenient.

        Marc

        Comment

        • =?Utf-8?B?VmljdG9y?=

          #5
          Re: Reflection: How to discover name of a property at run time.


          It does exactly what I have wished for!

          Looks a bit scary, but it does the job.

          The reason I been looking for that functionality is similar to the one
          described in the post you referred to.
          In my LINQ to SQL buz layer, to report errors, I have to name LINQ entity
          properties to blame as a reason for error.
          " .... at the moment I use strings, but if the property name on the class
          changes it causes runtime errors whereas I would prefer compile time errors.
          To be clear, I want the name of the property and not the value of a property
          of an instance. "

          The other place where I wished for it, is custom data binding, like
          MyFantasticBinf d(this.Textxbox 1, LINQEntity, "Property1" ), where again
          Propert1 is a string, and changes to LINQEntity wouldn't be recognized by
          compiler.

          Please let my voice to JOIN to those who are looking for the nameof(...)
          operator.

          Victor

          Comment

          • =?Utf-8?B?VmljdG9y?=

            #6
            Re: Reflection: How to discover name of a property at run time.

            Marc,

            thanks again for your reply. Using your code I was able to replace:

            AddBusinessErro r("cs_dt_receiv ed", "Received date can't be earlier than date
            of loss");
            to
            AddBusinessErro r<T_ComplainCas e, DateTime?>(x =x.cs_dt_receiv ed, "Received
            date can't be earlier than date of complain");

            where T_ComplainCase is LINQ to SQL autogenerated class, and cs_dt_received
            is one of the properties (i.e. SQL server table's column). This is much
            better for me, since now I can be sure that if somebody changes table on SQL
            server my code fails when compile.

            My question, in you is:
            In your post
            http://groups.google.com/group/micro...05324df6b30218 you have mentioned that:

            "In fact, add in some "this TType obj" and you get type inference... ".
            string test1 = foo.MemberName( x =x.Bar);

            Can you share that code with us?

            Thanks Victor.

            Comment

            • Marc Gravell

              #7
              Re: Reflection: How to discover name of a property at run time.

              I haven't checked (in a hurry), but:

              public static string MemberName<TTyp e>(
              this TType type,
              Expression<Acti on<TType>member )
              {
              return MemberInfo(memb er).Name;
              }

              public static string MemberName<TTyp e, TResult>(
              this TType type,
              Expression<Func <TType, TResult>member)
              {
              return MemberInfo(memb er).Name;
              }

              The "type" argument isn't used except by the compiler for the type-
              inference.

              Marc

              Comment

              • Marc Gravell

                #8
                Re: Reflection: How to discover name of a property at run time.

                Looks a bit scary, but it does the job.

                That phrase pretty-much describes most manual uses of Expression - a
                very confusing subject indeed! For info, though: it looks scary, but
                it gets easier with a little practice - you just need to take a very
                deep breath before diving in ;-p

                Marc

                Comment

                • =?Utf-8?B?VmljdG9y?=

                  #9
                  Re: Reflection: How to discover name of a property at run time.

                  And they worth diving in!

                  After looking at your elegant code I’ve realized how important Expressions
                  might be, and definitely want to spend some time learning more.

                  Also, when I have incorporated it in my application, I do not see it any
                  more “as largely "for jollies"”. I feel much more confident in biasness logic
                  layer now, than when the database fields (i.e. SQL LINQ properties) where
                  strings in my error reporting methods.

                  Since my original question was about getting names of the properties, I have
                  modified your code and introduced a delegate that returns object, so when
                  looking for a property name, I do not need to specify result type <TType,
                  TResult>, but just <TType>.

                  Actually, your code blows on such expressions, since Expression contains
                  Convert function that your code doesn’t expect ({x =>
                  Convert(x.cs_dt _received)}).

                  In the code below expression parsing is 'hard wired' (just for
                  illustration), so the place for UnitaryExpressi on is visible.

                  static class MemberUtil
                  {

                  public delegate object PropertyNameDel etgate<T>(T x);

                  public static string GetPropertyName <T(Expression
                  <PropertyNameDe letgate<T>membe r)
                  {
                  return ((MemberExpress ion) ((Expression) ((UnaryExpressi on)
                  member.Body).Op erand)).Member. Name;
                  //return MemberUtil.Pars eMemberInfo(mem ber).Name;
                  }
                  }


                  "Marc Gravell" wrote:
                  Looks a bit scary, but it does the job.
                  >
                  That phrase pretty-much describes most manual uses of Expression - a
                  very confusing subject indeed! For info, though: it looks scary, but
                  it gets easier with a little practice - you just need to take a very
                  deep breath before diving in ;-p
                  >
                  Marc
                  >

                  Comment

                  • Marc Gravell

                    #10
                    Re: Reflection: How to discover name of a property at run time.

                    I'm glad it was useful, then ;-p

                    Marc

                    Comment

                    Working...