tags:

views:

70

answers:

4

I've got an object containing 30 properties that I know the names of. The properties are called "ValueX" (1-30) where X is a number.

How would I call value1 - value30 in a loop?

+7  A: 

Using reflection.

public static string PrintObjectProperties(this object obj)
{
    try
    {
        System.Text.StringBuilder sb = new StringBuilder();

        Type t = obj.GetType();

        System.Reflection.PropertyInfo[] properties = t.GetProperties();

        sb.AppendFormat("Type: '{0}'", t.Name);

        foreach (var item in properties)
        {
            object objValue = item.GetValue(obj, null);

            sb.AppendFormat("|{0}: '{1}'", item.Name, (objValue == null ? "NULL" : objValue));
        }

        return sb.ToString();
    }
    catch
    {
        return obj.ToString();
    }
}
David Basarab
+1  A: 

You can do this with Reflection, getting the PropertyInfo objects for the class and checking the name of them.

Ian
+2  A: 

You may consider using a collection or a custom indexer, instead.

public object this[int index]
{
    get
    {
        ...
    }

    set
    {
         ...
    }
}

then you can say;

var q = new YourClass();
q[1] = ...
q[2] = ...
...
q[30] = ...
John Gietzen
Why the downvote? His question says "Value1" through "Value30" this is what custome indexers were MADE for.
John Gietzen
+1  A: 

The following will select all of the properties/values into a IEnumerable of an anonymous type that contains name/value pairs for the properties you are interested in. It makes the assumption that the properties are public and that you are accessing from a method of the object. If the properties aren't public you'll need to use BindingFlags to indicate that you want nonpublic properties. If from outside the object, replace this with the object of interest.

var properties = this.GetType()
                     .GetProperties()
                     .Where( p => p.Name.StartsWith("Value") )
                     .Select( p => new {
                           Name = p.Name,
                           Value = p.GetValue( this, null )
                      });
tvanfosson