Consider the following code:
DerivedClass drbObj = (DerivedClass)obj;
Here obj
is of type Object
and this is reasonable since Object is the base type of every Class in C#.
Here, since the type of derObj
is defined at compile time, what is the need to explicitly use type conversion here. Can't the compiler predict on it's own that it will be of DerivedClass
. I understand that, the Conversion type doesn't have to match the Derived
type, but for practical purpose, it will only be as useful as the Derived
type.
Could someone explain with a small, hypothetical example, as to why the Explicit Type Conversion is necessary when a reference of type Object is being assigned to a derived class.
From what I know, in C, there is no need to do perform Explicit type conversion from void*
to any pointer and the compiler can handle it, based on the type of the pointer to which the converted value is being assigned.
DerivedClass drbObj = (DerivedClass)obj;
whereclass DerivedClass : Object
was anInvalidCastException
howeverDerivedClass drgObj = obj as DerivedClass;
worked just fine. That may just be nit-picking though :)(SomeType)x
andx as SomeType
are two very different constructs in C# (don't know about other languages). The first is an assertion (you're willing to deal with the exception if the types are incompatible), the second is an attempt (and yieldsnull
if the types are incompatible).