Is it possible, if we use a Type as key for a dictionary, to constrain that type only to specific ones? For example:
public abstract class Base
{ }
public class InheritedObject1 : Base
{ }
public class InheritedObject2 : Base
{ }
public class Program
{
public Dictionary<Type, string> myDictionary = new Dictionary<Type, string>();
}
So from the code given above for instance i want to constraint the Type only to : Base and every class which inherits from it. Is it possible to make such a constraint?
Just create a template class that inherits from Dictionary
, as so:
class CustomDictionary<T> : Dictionary<T, string>
where T : Base
{
}
Then you can use it in your code as required:
public void Test()
{
CustomDictionary<InheritedObject1> Dict = new CustomDictionary<InheritedObject1>();
Dict.Add(new InheritedObject1(), "value1");
Dict.Add(new InheritedObject1(), "value2");
}
Well if you do
public Dictionary<Base, string> myDictionary = new Dictionary<Base, string>();
then only Base
and its children will be able to be used as the key (in this specific case Base
is abstract
so only children applies).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With