monkey_boys
monkey_boys

Reputation: 7348

How to get properties Names from object parameter?

i write some utility class but how to get name ? Can that send parameter Name to Mehod not use object.Name?

 class AutoConfig_Control  {
            public List<string> ls;
            public AutoConfig_Control(List<string> lv)
            {
                ls = lv;
            }
            public void Add(object t)
            {
                //t.Name;  << How to do this 
                //Howto Get t.Name in forms?

                ls.Add(t.ToString());
            }
        }
        class AutoConfig
        {
            List<string> ls = new List<string>();
            public string FileConfig
            {
                set;
                get;
            }

            public AutoConfig_Control Config
            {
                get {
                    AutoConfig_Control ac = new AutoConfig_Control(ls);
                    ls = ac.ls;
                    return ac;
                }
                //get;
            }

            public string SaveConfig(object t) {
                return ls[0].ToString();
            }
        }

Example For use.

    AutoConfig.AutoConfig ac = new AutoConfig.AutoConfig();
    ac.Config.Add(checkBox1.Checked);
    MessageBox.Show(ac.SaveConfig(checkBox1.Checked));

Upvotes: 1

Views: 477

Answers (2)

Beatles1692
Beatles1692

Reputation: 5320

Completing Rauhotz answer : Expression.Body might be a UnaryExpression (for boolean properties for example) Here's what you should do to work with these kind of expressions:

var memberExpression =(expression.Body is UnaryExpression? expression.Body.Operand :expression.Body) as MemberExpression;

Upvotes: 1

Rauhotz
Rauhotz

Reputation: 8140

The only way i know is a hack like this:

  /// <summary>
  /// Gets the name of a property without having to write it as string into the code.
  /// </summary>
  /// <param name="instance">The instance.</param>
  /// <param name="expr">An expression like "x => x.Property"</param>
  /// <returns>The name of the property as string.</returns>
  public static string GetPropertyName<T, TProperty>(this T instance, Expression<Func<T, TProperty>> expr)
        {
            var memberExpression = expr.Body as MemberExpression;
            return memberExpression != null
                ? memberExpression.Member.Name
                : String.Empty;
        }

If you place it in a static class you will get the extension method GetPropertyName.

Then you can use it in your example like

checkbox1.GetPropertyName(cb => cb.Checked)

Upvotes: 2

Related Questions