Search code examples
objectc#-3.0typescastingtype-safety

About casting and objects


it's simple, i just want a explanation about this:

internal class B { // Base class
}
internal class D : B { // Derived class
}

in other class I wrote:

B b3 = new Object(); //compilation time error!

why??? We suposse that all classes inherit from "object"


Solution

  • B is more specialized than Object, therefore you cannot assign an Object instance to a B reference. This is because not every Object is actually a B - only the opposite is true.

    Let's assume that you have a field x in the class B. When you instantiate an Object, no memory is reserved for this field, and if you could assign it to a reference of type B, it would therefore try to read or write to unallocated memory, which is not allowed (or useful).