Something about nothing » Convert an object to string in .net

Convert an object to string in .net

A while back I needed a way to take an object in C# and convert it to a string, this made it easy for loggin in case of errors I knew what was sent and what was received back. I wanted to set something up so I could recursively iterate over the object and pull out and child objects in arrays and such. It took a little bit of work to write up but I was finally able to accomplish this. Here is what I came up with. If you have any suggestions on improving this let me know.


public static string ConvertObjectToString(object Obj)
{
string sResult = "";
if (Obj != null)
{
Type objType;
PropertyInfo[] colPropertyInfo;
objType = Obj.GetType();
colPropertyInfo = objType.GetProperties();
//I don’t know how to get a generic list to be recursive so I hard coded the name “List`1″ hopefuly this is true
// maybe switch to something like: (objPropertyInfo.PropertyType != typeof(string) && !objPropertyInfo.PropertyType.IsPrimitive)
if (objType.Name == “List`1″ || objType.BaseType == typeof(System.Array))
{
foreach (object tempVar in Obj as IEnumerable)
{
sResult += ConvertObjectToString(tempVar);
}
}

else
{
foreach (PropertyInfo objPropertyInfo in colPropertyInfo)
{
if (objPropertyInfo.GetValue(Obj, null) != null)
{
sResult += objPropertyInfo.Name + “=” + objPropertyInfo.GetValue(Obj, null).ToString();
sResult += ”
“;
}
if (objPropertyInfo.PropertyType.BaseType == typeof(System.Array) || objPropertyInfo.PropertyType.Namespace == “System.Collections.Generic” || (objPropertyInfo.PropertyType != typeof(string) && !objPropertyInfo.PropertyType.IsPrimitive))
{
sResult += ConvertObjectToString(objPropertyInfo.GetValue(Obj, null));
}
}
}
}
return sResult;
}

I have some coments on where I hard coded some values. If there is a different way of doing this it would be greatly appreciated.

Published by admin on June 26th, 2009 | Filed under Uncategorized

Leave a Comment