Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a class member be declared virtual (C#)/Overridable (VB.NET)?

Tags:

c#

.net

vb.net

Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?

like image 316
Alex Angas Avatar asked Dec 05 '22 07:12

Alex Angas


2 Answers

An abstract method or property (both can be virtual or abstract) can only be declared in an abstract class and cannot have a body, i.e. you can't implement it in your abstract class.

A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty).

If someone want to use your abstract class, he will have to implement a class that inherits from it and explicitly implement the abstract methods and properties but can chose to not override the virtual methods and properties.

Exemple :

using System;
using C=System.Console;

namespace Foo
{
    public class Bar
    {
        public static void Main(string[] args)
        {
            myImplementationOfTest miot = new myImplementationOfTest();
            miot.myVirtualMethod();
            miot.myOtherVirtualMethod();
            miot.myProperty = 42;
            miot.myAbstractMethod();
        }
    }

    public abstract class test
    {
        public abstract int myProperty
        {
            get;
            set;
        }

        public abstract void myAbstractMethod();

        public virtual void myVirtualMethod()
        {
            C.WriteLine("foo");
        }

        public virtual void myOtherVirtualMethod()
        {
        }
    }

    public class myImplementationOfTest : test
    {
        private int _foo;
        public override int myProperty
        {
            get { return _foo; }
            set { _foo = value; }
        }

        public override void myAbstractMethod()
        {
            C.WriteLine(myProperty);
        }

        public override void myOtherVirtualMethod()
        {
            C.WriteLine("bar");
        }
    }
}
like image 58
Kokuma Avatar answered Dec 14 '22 23:12

Kokuma


You would use abstract if you do not want to define any implementation in the base class and want to force it to be defined in any derived classes. Define it as a virtual if you want to provide a default implementatio that can be overriden by derived classes.

Yes, only methods can be virtual.

like image 44
Phil Wright Avatar answered Dec 15 '22 00:12

Phil Wright