Skip to content

Instantly share code, notes, and snippets.

@fresky
Created July 17, 2012 07:02
Show Gist options
  • Save fresky/3127726 to your computer and use it in GitHub Desktop.
Save fresky/3127726 to your computer and use it in GitHub Desktop.
C# cast example
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