Working with .NET 2 in mono, I'm using a basic JSON
library that returns nested string, object Dictionary and lists.
I'm writing a mapper to map this to a jsonData class that I already have and I need to be able to determine if the underlying type of an object
is a Dictionary or a List. Below is the method I'm using to perform this test, but was wondering if theres a cleaner way?
private static bool IsDictionary(object o) {
try {
Dictionary<string, object> dict = (Dictionary<string, object>)o;
return true;
} catch {
return false;
}
}
private static bool IsList(object o) {
try {
List<object> list = (List<object>)o;
return true;
} catch {
return false;
}
}
The library I'm using is litJson
but the JsonMapper
class essentially doesn't work on iOS, hence the reason I am writing my own mapper.
Modifying the above answer. In order to use
GetGenericTypeDefinition()
you must preface the method withGetType()
. If you look at MSDN this is howGetGenericTypeDefinition()
is accessed:Here is the link: https://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition(v=vs.110).aspx
If you want to check that a certain object is of some type, use the
is
operator. For example:Though for something this simple, you probably don't need a separate method, just use the
is
operator directly where you need it.Use the
is
keyword and reflection.If you just need to detect the object is
List/Dictionary
or not, you can usemyObject.GetType().IsGenericType && myObject is IEnumerable
Here is some example: