When I cast a variable to type dynamic before passing it to a generic type parameter of a function, the next parameter is bypassing the type check.
In the below snippet, how is the first call to Check method escaping the compilation?
The (dynamic) casting is done only to the first argument (where a Type1 is passed to Interface1). But the second parameter where Type1 is passed to Interface2 is not failing in compilation.
interface Interface1 { }
interface Interface2 { }
class Type1 : Interface1 { }
class Type2 : Interface2 { }
class Program
{
public static void Check<T1, T2>(T1 obj1, T2 obj2) where T1 : Interface1 where T2 : Interface2
{
}
static void Main(string[] args)
{
Check((dynamic)new Type1(), new Type1()); //passes compliation and fails in runtime
Check(new Type1(), new Type1()); //fails in compilation
}
}
Using
dynamiccauses the generic type checking to be deferred until runtime. Once any any parameter isdynamicthen the whole thing is deferred, so in the first statement the singledynamiccauses the deferral.Without it, in the second statement, the checking is done at compile-time and so fails as a compiler error.
In both cases the call is invalid:
obj2cannot be ofType1becauseType1does not implementInterface2. It's just a question of when the error is caught.