0

For example,

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()
    {
        Foo test = new Bar();
        Console.WriteLine(test.DoSomething());
    }
}

Why is the answer True? What does "new Bar()" mean? Doesn't "new Bar()" just mean allocate the memory?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mike Liu
  • 69
  • 1
  • 7
  • 2
    Why would you expect it to be false? What would be the point in overriding the method? Perhaps you're interested in [method hiding](https://msdn.microsoft.com/en-us/library/aa691135(v=vs.71).aspx) ? – Rob Oct 26 '16 at 03:25
  • Possible duplicate of [C# keyword usage virtual+override vs. new](http://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new) – Alsty Oct 26 '16 at 10:54
  • I am thinking "Foo test" is to create an object test of Foo type, although "new Bar()" is set. I don't know if there is a better explanation of memory allocation and objection creation. That would be much clearer for me to understand. – Mike Liu Oct 27 '16 at 07:21

3 Answers3

5

new Bar() actually makes a new object of type Bar.

The difference between virtual/override and new (in the context of a method override) is whether you want the compiler to consider the type of the reference or the type of the object in determining which method to execute.

In this case, you have a reference of type "reference to Foo" named test, and this variable references an object of type Bar. Because DoSomething() is virtual and overridden, this means it will call Bar's implementation and not Foo's.

Unless you use virtual/override, C# only considers the type of the reference. That is, any variable of type "reference to Foo" would call Foo.DoSomething() and any "reference to Bar" would call Bar.DoSomething() no matter what type the objects being referenced actually were.

PMV
  • 2,058
  • 1
  • 10
  • 15
0

new Bar() means create a new Bar object and call the default constructor (which does nothing in this case).

It returns true because test.DoSomething() returns true, as it has an override for Foo implementation (so the Foo implementation will not be called).

0
Foo test = new Bar();

test is referring to a new object of Bar, hence the call test.DoSomething() calls the DoSomething() of the object Bar. This returns true.

Mukul Varshney
  • 3,131
  • 1
  • 12
  • 19