Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi dear developers,

Please observe the following C# code once.

C#
class BaseClass
    {
        public void Method1(){}
    }

    class DerivedClass : BaseClass
    {
        public void Method2(){}
    }

    class Program
    {
        static void Main()
        {
            BaseClass bc = new BaseClass();
            DerivedClass dc = new DerivedClass();
            BaseClass bcd = new DerivedClass();
            DerivedClass dcb = new BaseClass(); /*compile time error. Cannot implicitly convert type 'BaseClass' to 'DerivedClass'. An explicit conversion exists (are you missing a cast?)*/
        }
    }


When i am assigning the base class object to the derived class variable compiler throwing the error Cannot implicitly convert type 'BaseClass' to 'DerivedClass' . But, i am not getting the error when i am assigning the derived class object to the base class object.

Can you please clarify me why it is happening.
Posted

1 solution

You cannot automatically convert a base class instance into a derived class instance: it would involve the system "inventing" data. You can, if you create a specific cast operator because you can "fill in" the missing infor yourself, but I really don't recommend it at all.

Think about it: an Orange is a Fruit, but not all Fruits are Oranges - some are Apples.
If you create an instance of a Fruit, it is not an Orange or an Apple - it's a generic Fruit, which probably doesn't exist.

This is why you often see people create base classes as abstract so that you cannot even create an instance of them.
 
Share this answer
 
Comments
Vedat Ozan Oner 13-Feb-14 7:38am    
nice example. I like to think it such that:
BaseClass: small basket
DerivedClass: big basket

you can pour all water
from small => to small
from big => to big
from small => to big

but not
from big => to small. it overflows. compiler gives error :)
Srinubabu Ravilla 13-Feb-14 7:49am    
Nice explanation Thank you.
Sampath Lokuge 13-Feb-14 7:38am    
+5 :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900