Mike Liu
Mike Liu

Reputation: 79

create a variable of derived class to refer an object of base class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication12
{
    public class Foo
    {
        public virtual bool DoSomething() { return false; }
    }

    public class Bar : Foo
    {
        public override bool DoSomething() { return true; }
    }

    public class Test
    {
        public static void Main()
        {
            Bar test = new Foo();
            Console.WriteLine(test.DoSomething());
        }
    }
}

Error message:

Error CS0266 Cannot implicitly convert type 'ConsoleApplication12.Foo' to 'ConsoleApplication12.Bar'. An explicit conversion exists (are you missing a cast?) ConsoleApplication12 C:\Users\chliu\Documents\Visual Studio 2015\Projects\ConsoleApplication12\ConsoleApplication12\Program.cs

It seems "create a variable of derived class to refer an object by base class" is not allowed. Why?

Upvotes: 0

Views: 63

Answers (1)

meJustAndrew
meJustAndrew

Reputation: 6613

This does not work without a cast :

Bar test = (Bar)new Foo();

Other way around it is working:

Foo test = new Bar();

It is because a Bar can have things that a Foo doesn't and it would result into an unexpected behavior if you try to access these on the Bar object created from a Foo.

To be a little more explicit, you can ask yourself a question to understand better casting:

Is Foo a Bar? If yes, then the cast from Foo to Bar will work like in the following example:

Foo actuallyBar = new Bar();

Bar = (Bar)actuallyBar; //this will succeed because actuallyBar is actually a Bar

The other way of casting will always work because everytime you are asking if the Bar is a Foo the answer will be yes!

Foo foo = new Bar();//didn't even had to use explicit cast, because the compiler knows that Bar is a Foo

Upvotes: 2

Related Questions