Click here to Skip to main content
15,895,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
DerivedClass DerObj = new BaseClass();

Why is it not working? Can anyone please tell me the reason?
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass BaseObj = new DerivedClass();
            //any one please tell why its not working i dont want do costing i want reason.
            DerivedClass DerObj = new BaseClass();
        }
    }
    public class BaseClass
    {     
    }
    public class DerivedClass : BaseClass
    {
    }
}
Posted
Updated 4-Mar-14 5:15am
v2
Comments
Sergey Alexandrovich Kryukov 4-Mar-14 11:24am    
No, you please explain why do you think such gibberish is supposed to work.
—SA

You need to understand the runtime types vs compile-time types. And inheritance.
BaseObj has the compile-time type BaseClass, but actual runtime type is DerivedClass. By inheritance, DerivedClass can have some members not present in BaseClass, but the variable does not give you access to these added members. It's all fully acceptable. This is how polymorphism works.

The opposite situation would be unacceptable. The variable could get access to some members added only in derived class. But the actual runtime type is the base class. So, you would get access to the members which physically do not exist. It would be the disaster.

Is that clear?

—SA
 
Share this answer
 
Comments
Maciej Los 4-Mar-14 17:15pm    
+5!
Sergey Alexandrovich Kryukov 4-Mar-14 17:18pm    
Thank you, Maciej.
—SA
Solution 2 by Sergey Alexandrovich Kryukov is very good and i would like to add some extra links:
Inheritance (C# programming guide)[^]
Polymorphism (C# Programming Guide)[^]
Introduction to inheritance, polymorphism in C#[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Mar-14 17:19pm    
Sure, 5ed.
—SA
Maciej Los 4-Mar-14 17:20pm    
Thank you, Sergey ;)
C#
BaseClass baseObj = new DerivedClass();

works because, by definition, a DerivedClass object is implicitly a BaseClass.

C#
DerivedClass derObj = new BaseClass();

does not work because a BaseClass object is not systematically a DerivedClass ; it could be another object defined as derived from BaseClass, but different from DerivedClass.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Mar-14 11:31am    
I think this is not clear. You never mentioned the root of the problem: the members possibly added by inheritance.
Please see my answer.
—SA

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