Is there anything planned for implicit conversion of generics? #1596
-
Hello, So my problem is as follows, I'm writing a library that is similar to linq-expression trees. My problem lies in the following code, and I wonder if there could be anything done to make it so I can express this more easily. It does work, but it's not elegant at all.
I found one issue on here that is about being able to omit a part of the generic type definition when the compiler can infer it, but I don't think that's really relevant here, or is it? edit:I realized that the core of the problem can be shown in a simplified way:
This doesn't work:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
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 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 |
Beta Was this translation helpful? Give feedback.
-
I see, that makes sense. Good to know, thank you for clearing that up! |
Beta Was this translation helpful? Give feedback.
-
@rikimaru0345 __makeref is available directly. The IDE experience is just "broken" since the keyword is treated as undocumented. |
Beta Was this translation helpful? Give feedback.
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 changeExpression
to:As for why covariance is so limited and doesn't happen automatically, consider this code:
This code is clearly wrong, since it attempts to add
MemoryStream
(which…