Classes and delegates behave a little differently. Consider a simple example:
public void SomeMethod<T>(T arg) where T : MyInterface { MyInterface e = arg; }
In this method, you could assume that T will be at least MyInterface , so you can do something like this MyInterface e = arg; , because args can always be added to MyInterface .
Now let's see how delegates behave:
public class BaseClass { }; public class DerivedClass : BaseClass { }; private readonly IList<Action<BaseClass >> myActionList = new List<Action<BaseClass>>(); public void Subscribe<T>(Action<T> callback) where T: BaseClass { myActionList.Add(callback);
Now we add the DerivedClass callback to myActionList, and then you call delegates somewhere:
foreach( var action in myActionList ) { action(new BaseClass); }
But you cannot do this, because if you have a DerivedClass callback, you must pass it as DerivedClass as a parameter.
This question relates to covariance and contravariance . You can read about the deviation from this article, also Eric Lippert has some very interesting articles on variance, this is the first article, you can find the rest on his blog.
PS Edited commentary on Lee's commentary.
Andrew
source share