This is just a language syntax, but I guess the reason is that the IL
instruction that this expression emits expects a type metadata token. It
cannot be generated at compile type if you use a variable that doesn't have
value at compile time. Keep in mind that the IL instruction for conversion
*castclass* converts only to/from classes and itnerfaces that are in
base/derived class relationship or the interface is implemented by the type.
All other convrsion techniques like IConvertible, TypeConverter or type
casting operators overloading (C#) is not taken into account. All such
conversions has to be done explicitly by the progeammer or the compiler.
They are not part of the .NET Runtime so to speak.
Dynamic conversion cannot be provided out of the box. The one who writes the
class only know how to convert it to/from another type. For example how
could the runtyme know how to cnonvert from string to Foo. Only me (the
programmer who wrote this foo class) knows how to do that and if this
conversion makes any sense after all. The framework provides an
infrastructure for dynamic conversion
IConvertible and Convert class, or TypeConverter, but the implementation is
up to the developer.
The sample that I gave
(typeof(MyType))var?
doesn't make much sense because this line can be re-written simply to
(MyType)var and it will compile.
but this (what actually I wanted to demonstrate) is not possible
Type t = var1.GetType();
var1 = (t)var2; // at compile tyme t doesn't have value.
--
Stoitcho Goutsev (100) [C# MVP]
"Nick Weekes" <ni***********@yahoo.co.uk> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Stoitcho,
Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?
Cheers,
Nick