✅ typeof()?
I am trying to arrange objects in a hashmap:
The key should be the class and the Value a List with the instances of this class.
Is typeof ()the right function for this?
8 Replies
Does your hashmap look like
Dictionary<Type, Object>()
?
You can indeed obtain a Type
object representing your class using typeof(MyClass)
.
If you don't know the class at compile time, you can use myClassInstance.GetType()
to get a Type
instance representing MyClass
at runtime.Thanks
I will try to implement that
Note that, given:
You can do
typeof(string)
, but typeof(foo)
makes no sense. The thing you pass to typeof
has to be a type, not a variable.
If you have:
Then again you can do typeof(T)
.Oh
If you have a variable and you want to get its runtime type, that's then
GetType() is used
. Note that this might not be the same as its compile-time type:
okay thank you
That is exactly the thing i need
So when you do the
Dictionary<Type, object>
thing, you'd normally have generic Add and Get methods, and you'd use typeof(T)
in themOkay thanks