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
You need to check whether
GetGenericTypeDefinition()
returns typeof(Dictionary<,>)
using
dict.GetGenericTypeDefinition()
? The method doesn't existOn 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 noI want to make sure the parameter is a Dictionary of any type
And not a string, int etc
This doesn't seem right
Yeah so... why?
Just do this
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 thingsI 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
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
I come from JS/Python, so yea lol
I normally type check stuff
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#We have a compiler to do that automatically. That's kinda of the point of strongly-typed languages
Good to know
ty