Getting String Value for All Object’s Properties

In last post I wen't through task of restoring properties from their textual representation. But how did we end up with text?

It is as simple as loop through all public properties and then using TypeConverter in order to properly convert a value to it's string representation. Do notice that ConvertToInvariantString is preferred over ConvertToString in order for code to properly work on non-USA Windows.

public static IDictionary<string, string> GetPairs(object objectInstance) {
var result = new Dictionary<string, string>();
foreach (var propertyInfo in objectInstance.GetType().GetProperties()) { //loops through all public properties
var propertyConverter = TypeDescriptor.GetConverter(propertyInfo.PropertyType); //gets converter for property
var stringValue = propertyConverter.ConvertToInvariantString(propertyInfo.GetValue(objectInstance, null)); //converts value to string
result.Add(propertyInfo.Name, stringValue);
}
return result;
}

P.S. Saving key/value pairs to file is not shown here... guess how it is done... :)

Leave a Reply

Your email address will not be published. Required fields are marked *