C
C#3mo ago
KleinRiese

✅ 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
SleepWellPupper
SleepWellPupper3mo ago
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.
KleinRiese
KleinRieseOP3mo ago
Thanks I will try to implement that
canton7
canton73mo ago
Note that, given:
string foo = "";
string foo = "";
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:
public void Add<T>(T foo)
{
// ...
}
public void Add<T>(T foo)
{
// ...
}
Then again you can do typeof(T).
KleinRiese
KleinRieseOP3mo ago
Oh
canton7
canton73mo ago
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:
object foo = "";
typeof(object) // object
foo.GetType() // string
object foo = "";
typeof(object) // object
foo.GetType() // string
KleinRiese
KleinRieseOP3mo ago
okay thank you That is exactly the thing i need
canton7
canton73mo ago
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 them
KleinRiese
KleinRieseOP3mo ago
Okay thanks
Want results from more Discord servers?
Add your server