Search code examples
c#genericscontravariance

Store multiple contravariant delegates in a dictionary


I have following statement:

private delegate ITask<Id> CreateObjectDelegateAsync<in T>(T @object)
    where T : Model.Object;

And I want to store that in a dictionary:

Dictionary<Type, CreateObjectDelegateAsync<Model.Object>>

Now I am getting errors since T is not covariant and he can't convert it. I have multiple delegates with a derived T that need to be inside that dictionary.

T must be invariant in order for it to be usable as a type in the parameters. Any ideas or workarounds for this?


Solution

  • So the solution was quite simple: While I can't do it with invariance here directly, I can just use a:

    Dictionary<Type, Delegate>
    

    instead. I can assign any delegate to that no matter the generic type. Then later when getting the delegate I will just need to cast it to

    CreateObjectDelegateAsync<T>
    

    again.

    Like so (given that T is an existing type in the dictionary):

    (CreateObjectDelegateAsync<T>)DelegateDictionary[typeof(T)]