Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    class A
    {
    }
    class B:A
    {
    }
    class c
    {
        static void Main(string[] args)
        {
            B obj1 = new A();
        }
    }
}


Will it execute ??..and if not.. can anyone give me the exact answer ???
Posted
Updated 16-Sep-10 1:28am
v2

If B is a subclass of A then I think

A obj1 = new B() is fine but not vice versa


you can use a superclass to ref a subclass but not a subclass to ref a superclass


you might be able to cast it though
 
Share this answer
 
v2
Comments
arindam2010 16-Sep-10 7:50am    
Reason for my vote of 5
Automatic vote of 5 for accepting answer.
No, it won't execute.

If you write A obj1 = new B();, it will execute.

Why?

Because, A is the base class and B is the class that extends B. So, according to OOP, B "is a" A as A is in upper position in the inheritance hirarchy. So, it is always possible to assign an object of B to a reference of A. But, the opposite wouln't execute.

However, If you cast the object as follows, then it will compile, but, won't execute:

B obj1 = (B)new A();
 
Share this answer
 
v2
Comments
Kubajzz 16-Sep-10 7:33am    
Actually your last sentence is not exactly true. It will compile, but it will not execute, because an exception will be thrown at runtime... Good answer anyway, have my 4.
Hiren solanki 16-Sep-10 7:34am    
Good Answer
Dalek Dave 16-Sep-10 7:37am    
Good Call.
arindam2010 16-Sep-10 7:50am    
Reason for my vote of 5
Automatic vote of 5 for accepting answer.
Al-Farooque Shubho 16-Sep-10 10:11am    
Good catch Kubajzz. Yes, I actually wanted to mean "Compile" not "execute". Slip of pen :) (Updated the answer accordingly).

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