C
C#2y 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
MODiX2y 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
ero2y ago
Weird
Cattywampus
Cattywampus2y 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
phaseshift2y 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
LPeter19972y 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
Cattywampus2y ago
you can as well check the interface if it's IDictionary or not with Type.IsAssignableFrom(Type) depends on what you want
Cattywampus
Cattywampus2y 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
skyrbunnyOP2y ago
that worked, thank you Can I use this for a Func<> delegate?
Aaron
Aaron2y ago
sure you just need the right amount of commas
MODiX
MODiX2y 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
skyrbunnyOP2y ago
I eventually figured it out, thanks. boy there's a lot of repetition
Accord
Accord2y 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.
Want results from more Discord servers?
Add your server