G
Guest
Hello,
I was wondering if C# 3.0 finally supported generic upcasting. Consider the
following code which does work in C# 2:
string[] xs = {"this", "is", "a", "test"};
object[] ys = xs;
Now, analogously, I would expect the following to work as well:
IEnumerable<string> xs = new string[] { "this", "is", "a", "test" };
IEnumerable<object> ys = xs;
As of now, this doesn't work because C# is unable to perform the conversion.
Actually, it is obvious why this code doesn't work: it would require the
creation of a new object, an operation which is not generally supported for
generics at the moment.
However, there is actually no technical reason not to allow this in general
(a proposed solution would have the compiler generate implicit conversion
methods, which, unfortunately, is not possible at the moment either because
the current version of C# does not allow to formulate the required
constraint).
So, long story short, my question: Does this work in C# 3.0? And if it
doesn't: Is there a sensible reason for this? I need this kind of code
constantly and the workarounds I have to use are nothing short of annoying.
I was wondering if C# 3.0 finally supported generic upcasting. Consider the
following code which does work in C# 2:
string[] xs = {"this", "is", "a", "test"};
object[] ys = xs;
Now, analogously, I would expect the following to work as well:
IEnumerable<string> xs = new string[] { "this", "is", "a", "test" };
IEnumerable<object> ys = xs;
As of now, this doesn't work because C# is unable to perform the conversion.
Actually, it is obvious why this code doesn't work: it would require the
creation of a new object, an operation which is not generally supported for
generics at the moment.
However, there is actually no technical reason not to allow this in general
(a proposed solution would have the compiler generate implicit conversion
methods, which, unfortunately, is not possible at the moment either because
the current version of C# does not allow to formulate the required
constraint).
So, long story short, my question: Does this work in C# 3.0? And if it
doesn't: Is there a sensible reason for this? I need this kind of code
constantly and the workarounds I have to use are nothing short of annoying.