Mark A. Donohoe
Mark A. Donohoe

Reputation: 30368

Can you restrict the type of Type in a generic?

I have a dictionary where both the key and values are of type Type, like so...

private static Dictionary<Type, Type> myDict;

What I'm trying to do is restrict the second Type to only be types which inherit from FrameworkElement.

Note I'm not storing FrameworkElement instances, I'm trying to only store objects of type Type which derive from FrameworkElement making the following statement true...

var isTypeStorable = typeof(FrameworkElement).IsAssignableFrom(FooType);

So can that be done?

BTW, yes, I know I can use the above to do runtime checking before adding to the dictionary (which is what I'm doing now). I'm wondering if there's any features in the language which would let me restrict this at compile time.

Upvotes: 4

Views: 95

Answers (2)

nvoigt
nvoigt

Reputation: 77295

No, that's not possible. FrameworkElement.GetType() and FooType have no relationship in the type system, both are just Types. If you want to restrict your generic, you will have to do so with runtime checks and exceptions, the generic constraints will not help you here.

If you know what you want to store at compile time (or are happy with some complicated reflection) you could change your API to not take Type, but use the generic instead:

public void AddTypeForType(Type x, Type y)

could be replaced by

public void AddTypeForType<T1, T2>() where T1 : FrameworkElement
{
    myDict.Add(typeof(T1), typeof(T2));
}

You could then call it like this:

AddTypeForType<FrameworkDerivedClass, MyCustomClass>();

But that's more of an API change than an answer to your question.

Upvotes: 4

sujith karivelil
sujith karivelil

Reputation: 29006

I think there is nothing like that, But you can achieve this by checking the items before adding to the dictionary, I meant something like this:

Let Xx,Yy be an item that I wanted to add to the myDict SO what I can do is, First check for the existence of key and then for the condition for value(inherit from FrameworkElement.)

if(!myDict.ContainsKey(Xx) && /* Yy is inherited from FrameworkElement */)
{
   myDict.Add(Xx,Yy);
}

Upvotes: 1

Related Questions