C
C#2mo 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
SleepWellPupper2mo 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
KleinRiese2mo ago
Thanks I will try to implement that
canton7
canton72mo 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
KleinRiese2mo ago
Oh
canton7
canton72mo 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
KleinRiese2mo ago
okay thank you That is exactly the thing i need
canton7
canton72mo 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
KleinRiese2mo ago
Okay thanks
Want results from more Discord servers?
Add your server