variable class property RRS feed

  • Question

  • User2003575416 posted

    I have class1 with proporty p1p, p2p, p3p....p10001p...ect

    now depend on pass parameter n (it is integer) I need to access class1.pnp

    is there anyway to do that?

    Friday, June 27, 2014 1:55 PM


  • User281315223 posted

    You may be able to access it via Reflection as mentioned in this similar Stack Overflow discussion :

    public static object GetPropValue(object src, string propName)
         return src.GetType().GetProperty(propName).GetValue(src, null);

    You could expand it to something like the following :

    public class YourClass
            public int Property1 { get; set; }
            public int Property2 { get; set; }
            public int Property3 { get; set; }
            public int GetPropertyByInteger(int n)
                // Build your property name here
                var propertyName = String.Format("p{0}p", n);
                return Convert.ToInt32(this.GetType().GetProperty(propertyName).GetValue(this, null));

    which would allow you to reference your property by just passing in the index you needed :

    var property3 = YourClass.GetPropertyByInteger(3);

    Another solution would be to write a custom indexer that is similar to the above method (and still uses Reflection) and set it on your class :

    public class YourClass
            public int p1p { get; set; }
            public int p2p { get; set; }
            public int p3p { get; set; }
            public int this[int n]
                    return Convert.ToInt32(this.GetType().GetProperty(String.Format("p{0}p",n)).GetValue(this, null));

    which would allow you to reference your properties via :

    // Access your class via a property name
    int property1 = yourClass[1];

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 27, 2014 3:13 PM