views:

102

answers:

2

For example I have a simple class like

public class Person{ 
    public int Age {get;set;}
    public string Name {get;set;}
}

I need to make a method that takes any class and spits out values of properties set in the object as a string in format "Age:35;Name:John Doe;"

I am looking for a method signature on the lines of

public string SpitNameValuePairs<T>()

or something like it. How can this be done efficiently if using reflection?

+2  A: 

Here is a quick implementation.

    public static string SplitNameValuePairs(object value)
    {
        string retVal = string.Empty;
        List<string> keyValuePairs = new List<string>();

        foreach (var propInfo in value.GetType().GetProperties())
        {
            keyValuePairs.Add(string.Format("{0}:{1};", propInfo.Name, propInfo.GetValue(value, null).ToString()));
        }

        retVal = string.Join("", keyValuePairs.ToArray());

        return retVal;
    }

Then called like this:

        var person = new Person();
        person.Name = "Hello";
        person.Age = 10;
        Console.WriteLine(SplitNameValuePairs(person));
Tom Anderson
If you just make it an extension method, you don't need the generic typing.
Tom Anderson
I just came to the almost this exact implementation. The only issue about is I've heard this is very slow (between 10X-1000X slower if I recall correctly). This also only deals with simple properties (i.e. not indexed, thats what the null argument to GetValue does).
Jason Punyon
Your solution is incomplete, you should add check for indexers and filtering for static properties. Since GetProperties() returns array you can use Array.ConvertAll which will be faster.
Dmitriy Matveev
like i said, quick.
Tom Anderson
+1  A: 

That have protection from crashes when property have an indexer defined and also it output only instance properties (no static).

    private static string SplitNameValuePairs<T>(T value)
    {
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
        {
            if (property.GetIndexParameters().Length == 0)
                sb.AppendFormat("{0}:{1};", property.Name, property.GetValue(value, null));
        }
        return sb.ToString();
    }
Dmitriy Matveev