views:

830

answers:

3

Let's say I have many objects and they have many string properties.

Is there a programatic way to go through them and output the propertyname and its value or does it have to be hard coded?

Is there maybe a LINQ way to query an object's properties of type 'string' and to output them?

Do you have to hard code the property names you want to echo?

+15  A: 

Use reflection. It's nowhere near as fast as hardcoded property access, but it does what you want.

The following query generates an anonymous type with Name and Value properties for each string-typed property in the object 'myObject':

var stringPropertyNamesAndValues = myObject.GetType()
    .GetProperties()
    .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
    .Select(pi => new 
    {
        Name = pi.Name,
        Value = pi.GetGetMethod().Invoke(myObject, null)
    });

Usage:

foreach (var pair in stringPropertyNamesAndValues)
{
    Console.WriteLine("Name: {0}", pair.Name);
    Console.WriteLine("Value: {0}", pair.Value);
}
Ben M
+1 Too fast! :)
Andrew Hare
+2  A: 

You can use reflection to do this... . there is a decent article at CodeGuru, but that may be more than you are looking for... you can learn from it, and then trim it to your needs.

Michael Bray
A: 

How about something like this?

public string Prop1
{
    get { return dic["Prop1"]; }
    set { dic["Prop1"] = value; }
}

public string Prop2
{
    get { return dic["Prop2"]; }
    set { dic["Prop2"] = value; }
}

private Dictionary<string, string> dic = new Dictionary<string, string>();
public IEnumerable<KeyValuePair<string, string>> AllProps
{
    get { return dic.GetEnumerator(); }
}
Axl