Skip to content
Discussion options

You must be logged in to vote

IEnumerator<int> implements IDisposable, so why can't it be converted?

The feature you're looking for is called covariance. C# does support covariance in interfaces (and delegates), but it has to be explicitly declared by using the out keyword on the type parameter. That means your code will compile if you change Expression to:

interface Expression<out T> { }

As for why covariance is so limited and doesn't happen automatically, consider this code:

static void AddToList<TObject>(List<TObject> list, TObject value)
{
    list.Add(value);
}

List<IEnumerator<int>> e = null;
CallInst<IDisposable>(e, new MemoryStream());

This code is clearly wrong, since it attempts to add MemoryStream (which…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by YairHalberstadt
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #1596 on October 16, 2020 04:12.