C
C#17mo ago
skyrbunny

❔ Type is Typeof Dictionary

I need to test if a System.Type t is a Dictionary of any kind, but when I do this check, it doesn't pass it. How do I test for this?
if (t == typeof(Dictionary<,>))
{
Debug.Log("Dictionary");
return $"{{{ConvertType(t.GenericTypeArguments[0])}:{ConvertType(t.GenericTypeArguments[1])}}}";
}
if (t == typeof(Dictionary<,>))
{
Debug.Log("Dictionary");
return $"{{{ConvertType(t.GenericTypeArguments[0])}:{ConvertType(t.GenericTypeArguments[1])}}}";
}
I did a log of the type.tostring after and it said
System.Collections.Generic.Dictionary`2[System.String,System.Object]
System.Collections.Generic.Dictionary`2[System.String,System.Object]
so I believe it is indeed a dictionary. Shouldn't it have passed the check?
12 Replies
MODiX
MODiX17mo ago
Ero#1111
REPL Result: Success
Dictionary<string, int> dict = new();

dict.GetType() == typeof(Dictionary<,>)
Dictionary<string, int> dict = new();

dict.GetType() == typeof(Dictionary<,>)
Result: bool
False
False
Compile: 470.383ms | Execution: 30.074ms | React with ❌ to remove this embed.
ero
ero17mo ago
Weird
Cattywampus
Cattywampus17mo ago
var t = dict.GetType();
bool amIDict = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
var t = dict.GetType();
bool amIDict = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
phaseshift
phaseshift17mo ago
typeof(Dictionary<,>) is not a pattern match type. It is the generic type definition/open generic type. You cannot create something with that type So a real dictionary will never have the same type as an open generic type
LPeter1997
LPeter199717mo ago
What you were comparing it to is an instance of this generic type. The solution is to ask for the generic definition, like BadaBingBadaBoom showed
Cattywampus
Cattywampus17mo ago
you can as well check the interface if it's IDictionary or not with Type.IsAssignableFrom(Type) depends on what you want
Cattywampus
Cattywampus17mo ago
Type.IsAssignableFrom(Type) Method (System)
Determines whether an instance of a specified type c can be assigned to a variable of the current type.
skyrbunny
skyrbunny17mo ago
that worked, thank you Can I use this for a Func<> delegate?
Aaron
Aaron17mo ago
sure you just need the right amount of commas
MODiX
MODiX17mo ago
Windows10CE#8553
REPL Result: Success
var f = (int a, int b, int c) => 4;
f.GetType().GetGenericTypeDefinition() == typeof(Func<,,,>)
var f = (int a, int b, int c) => 4;
f.GetType().GetGenericTypeDefinition() == typeof(Func<,,,>)
Result: bool
True
True
Compile: 533.683ms | Execution: 59.212ms | React with ❌ to remove this embed.
skyrbunny
skyrbunny17mo ago
I eventually figured it out, thanks. boy there's a lot of repetition
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.