Reputation: 803
I want to create a generic delegate. It will delegate functions that have generic types as parameter.
For example : I have an interface :
public interface IProblemState<T> : IComparable<IProblemState<T>>, IEquatable<IProblemState<T>>
where T : IEquatable<T>
{}
And I have two different class
public class Class1 : IEquatable<Class1>
{ }
public class Class2 : **IProblemState<Class1>**
{ }
And after I have an delegate
public delegate SortedSet<IProblemState<T>> ExpanderDelegate<T>(IProblemState<T> currentState)
where T : IEquatable<T>;
I can NOT create a delegate with a function that have derived class parameter (Instance of Class 2).
For Example :
SortedSet<**Class2**> expander(**Class2** currentState)
{}
ExpanderDelegate<Class2> expanderDel = new ExpanderDelegate(**expander**);
When I want to create delegate, I get below error.
No overload for 'expander' matches delegate 'ExpanderDelegate'
I want to use this delegate with all function that have derived parameters.
Is it possible with C#?
Thanks.
Upvotes: 0
Views: 612
Reputation: 10201
Of course you cannot. The delegate says: give me a function that can take any IProblemState<T>
as a parmeter, and you give it a function that can only take Class2
.
What if there were a Class3
that also implements IProblemState<T>
? Surely, the delegate signature says I should be able to pass an instance of Class3
in as a parameter. But the function wouldn't allow it (it only allows Class2
instances). That's why that function cannot be assigned to a variable of that delegate type.
What you can do, is use this generic delegate:
public delegate SortedSet<T> ExpanderDelegate<T,U>(T currentState)
where T : IProblemState<U> where U: IEquatable<U>;
Upvotes: 1