Reputation: 2565
Here is the code:
interface IA
{
}
interface IC<T>
{
}
class A : IA
{
}
class CA : IC<A>
{
}
class Program
{
static void Main(string[] args)
{
IA a;
a = (IA)new A(); // <~~~ No exception here
IC<IA> ica;
ica = (IC<IA>)(new CA()); // <~~~ Runtime exception: Unable to cast object of type 'MyApp.CA' to type 'MyApp.IC`1[MyApp.IA]'.
}
}
Why am I getting the casting exception in the last line of the code ?
Upvotes: 1
Views: 108
Reputation: 1022
you can do
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
interface IPerson
{
}
//Have to declare T as out
interface ICrazy<out T>
{
}
class GTFan : IPerson
{
}
class CrazyOldDude : ICrazy<GTFan>
{
}
class Program
{
static void Main(string[] args) {
IPerson someone;
someone = (IPerson)new GTFan(); // <~~~ No exception here
ICrazy<GTFan> crazyGTFanatic;
ICrazy<IPerson> crazyPerson;
crazyGTFanatic = new CrazyOldDude() as ICrazy<GTFan>;
crazyGTFanatic = (ICrazy<GTFan>)(new CrazyOldDude());
crazyPerson = (ICrazy<IPerson>)crazyGTFanatic;
}
}
}
Upvotes: 1