Recently I've run into strange issue related to casting. Every discussion/post I've seen tends to revolve around using casting when one is sure about the object being casted plus a couple of details. I haven't however found what's the reasoning behind the code below:
class Program
{
static void Main(string[] args)
{
var h = new SomeCommandHandler();
var c = h as ICommandHandler<ICommand>; //this works as expected
//var c = (ICommandHandler<ICommand>)h; //this throws - why?
}
interface ICommand { }
class SomeCommand : ICommand { }
interface ICommandHandler<I> where I : ICommand { }
class SomeCommandHandler : ICommandHandler<SomeCommand> { }
}
So why the second call throws an exception? What's the difference between casting and as operator that I'm not aware of?
EDIT: It wpuld throw in the commented line above "Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'SomeCommandHandler' to type 'ICommandHandler`1[ConsoleApplication1.Program+ICommand]'"