Check if an object is a Dictionary of any type

I'm trying to type-check a method parameter using if (dict.GetType() == typeof(Dictionary)). How can I check for all types of Dictionary without having to write them all out. Or am I wasting my time here, since the language has type-checking anyway?
12 Replies
Thinker
Thinker4mo ago
You need to check whether GetGenericTypeDefinition() returns typeof(Dictionary<,>)
UnemployedNinja
UnemployedNinja4mo ago
using dict.GetGenericTypeDefinition()? The method doesn't exist
Thinker
Thinker4mo ago
On the type of the dictionary dict.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>) Although if you already know that dict is a dictionary, why do you need this? oh I misread wait no
UnemployedNinja
UnemployedNinja4mo ago
I want to make sure the parameter is a Dictionary of any type And not a string, int etc
c#
dict1.GetType().GetGenericTypeDefinition() == typeof(Dictionary<object, object>).GetGenericTypeDefinition())
c#
dict1.GetType().GetGenericTypeDefinition() == typeof(Dictionary<object, object>).GetGenericTypeDefinition())
This doesn't seem right
Thinker
Thinker4mo ago
Yeah so... why? Just do this
public void YourMethod<TKey, TValue>(Dictionary<TKey, TValue> dict)
{
// ...
}
public void YourMethod<TKey, TValue>(Dictionary<TKey, TValue> dict)
{
// ...
}
canton7
canton74mo ago
Why did you read dict.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>), but try and do dict1.GetType().GetGenericTypeDefinition() == typeof(Dictionary<object, object>).GetGenericTypeDefinition())? Those are two very different things
UnemployedNinja
UnemployedNinja4mo ago
I have no idea tbh, I literally just started learning C# like two days ago lol idk what I'm doing I'm just playing around atm, trial and error Making random useless console apps
Thinker
Thinker4mo ago
You don't need to do these kinds of type checks yourself, ever The compiler does that for you We're not banging stones together, we're not Python
UnemployedNinja
UnemployedNinja4mo ago
I come from JS/Python, so yea lol I normally type check stuff
Thinker
Thinker4mo ago
If a method takes a Dictionary<int, string> then it can only take a Dictionary<int, string> That's a fundamental universal truth of C#
canton7
canton74mo ago
We have a compiler to do that automatically. That's kinda of the point of strongly-typed languages
UnemployedNinja
UnemployedNinja4mo ago
Good to know ty