Reputation: 79
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?
Upvotes: 0
Views: 361
Reputation: 2148
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.
Upvotes: 5
Reputation: 3141
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.
Upvotes: 0
Reputation: 21
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).
Upvotes: 0