To add to the Solutions 1 and 2:
The reason for these casting rule is some extra members added to the derived class. Consider this:
class Base {
internal int A { get; set; }
}
class Derived : Base {
internal int B { get; set; }
}
class AnotherDerived : Base { }
As you understand, there are instance properties
Base.A
,
Derived.A
,
AnotherDerived.A
and
Derived.B
. And, importantly, no
AnotherDerived.B
.
Imaging, for example, that you could have successful assignment
Derived derived = new AnotherDerived();
derived.B = 13;
It would give you access to
derived.B
, which is, in turn, would be the access to non-existing member, because
runtime type is actually
AnotherDerived
. That's why the
dynamic cast is used:
Base @object = new
Derived derived = @object as Derived;
if (derived != null)
derived.B = 15;
Note that the actual use of dynamic type check and casting, being a part of OOP, is considered as violation of OOP. Indeed, if you have such need, it suggests that the object hierarchy is not reasonably planned. There are rare reasonable exclusions though. They are only reasonable when they are rare. Your code should not be fundamentally based on it.
See also:
http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx[
^],
http://msdn.microsoft.com/en-us/library/scekt9xw.aspx[
^].
—SA