Created
July 17, 2012 07:02
-
-
Save fresky/3127726 to your computer and use it in GitHub Desktop.
C# cast example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class C<T> {} | |
internal class D | |
{ | |
public static C<U> M<U>(C<bool> c) | |
{ | |
// Fail compiling: | |
// return (C<U>)c; | |
// Pass compiling, exception in runtime: | |
// return X.Cast<C<U>>(c); | |
// Pass compiling, exception in runtime: | |
return (C<U>)(object)c; | |
} | |
} | |
public static class X | |
{ | |
public static V Cast<V>(object obj) | |
{ | |
return (V) obj; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
C<bool> c = new C<bool>(); | |
D.M<int>(c); | |
var enumerable = from bool b in new int[] {1, 2} select b; | |
foreach (var element in enumerable) | |
{ | |
Console.WriteLine(element); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment