Reputation: 283
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?
Upvotes: 4
Views: 6719
Reputation: 28097
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).
Upvotes: 1
Reputation: 16423
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");
}
Upvotes: 8