Mike Liu Mike Liu - 1 month ago 7
C# Question

c# new in object declaration when inherit and override

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?

PMV PMV
Answer

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.

Comments