I have a helper method that accepts parameters with generic types. This method can throw exceptions, which I log in order to debug later. Some objects have ids, some have names, etc., that would be useful to know when trying to debug. How can I log this information in a useful way?
How to identify generic objects in exception logs?
129 views Asked by Jason At
2
There are 2 answers
0
On
This function returns a C# style type name (something like List<String>
or List<Dictionary<Int32,String>>
) from a type.
public static string FancyTypeName(Type type)
{
var typeName = type.Name.Split('`')[0];
if (type.IsGenericType)
{
typeName += string.Format("<{0}>", string.Join(",",
type.GetGenericArguments().Select(v => FancyTypeName(v)).ToArray())
);
}
return typeName;
}
Regardles if it is a generic method or not, unless your object is null, you can log the type with
myObject.GetType().ToString()
EDIT:
If you would like to read more information from the object then you can read object properties like this:
This should work without any problems for primitives. For Objects it depends on how the ToString method is implemented. Also note that it will not read recursively, just the direct members of the class.