Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are methods "virtual" by default or "not virtual"?:

Tags:

c#

oop

According to this similar StackOverflow question and other articles, C# methods are "not virtual" by default, which I take it to mean that you cannot override them in a derived class.

If that is true, could you please explain to me how, in the example below, how I am able to implement the property LastName in the Child class which inherits from Base class without the property being marked as "virtual" inh the base class? Does the Child.LastName property "hide" (VB "Shadows") the same property in the base class? if so, why is the "new" key word not used in the Child.LastName pproperty to indicate this?

This test example seems to suggest to me that methods and virtual by default and, in the case of the LastName property, "overrrides" is implied, but I'm pretty sure that this is not the case.

What am I missing?

public class BaseClass
{

    private string _FirstName;
    public virtual string FirstName {
        get { return _FirstName; }
        set { _FirstName = value; }
    }

    private string _LastName;
    public string LastName {
        get { return _LastName; }
        set { _LastName = value; }
    }

    public void Go()
    {
        MessageBox.Show("Going at default speed in Base Class");
    }

    public void Go(int speed)
    {
        MessageBox.Show("Going at " + speed.ToString() + " in Base Class");
    }
}


public class Child : BaseClass
{

    public override string FirstName {
        get { return "Childs First  Name"; }
        set { base.FirstName = value; }
    }

    public string LastName {
        get { return "Child's Last Name"; }
        set { base.LastName = value; }
    }

    public void Go()
    {
        MessageBox.Show("Going in Child Class");
    }

    public void Go(int speed)
    {
        MessageBox.Show("Going at " + speed.ToString() + " in Child Class");
    }

}
like image 321
Chad Avatar asked Dec 27 '22 07:12

Chad


2 Answers

Methods are not virtual in C# by default. LastName in Child class hides the LastName from the BaseClass. As far as i can remember, this code can even compile, but warning will be provided by compiler, telling that new keyword should be used.

like image 117
alex Avatar answered Dec 30 '22 09:12

alex


They're non-virtual by default.

The subclass hides the base's LastName property.

If you write:

BaseClass b = new Child(...);
Console.WriteLine(b.LastName);

You will see the base implementation is called.

The compiler will warn you about this when you compile the above code. It's standard practice to mark a member which hides a base's member as new.

public new string LastName {
    get { return "Child's Last Name"; }
    set { base.LastName = value; }
}

This is a very common C# programming interview question :)

like image 25
Drew Noakes Avatar answered Dec 30 '22 09:12

Drew Noakes