The "virtual" keyword in C#

The "virtual" keyword in C#

Using the "virtual" modifier with a method in a parent class allows you to override the method in a child class in order to give it a different function within the child class, it can also be used for indexers and event declarations.

A good example of this would be the ToString() method.

image.png

If you were to try to add the virtual keyword to the ToString() method it would simply create a new version detached from the deriving class, which is why you would want to use the override keyword for this.

Constraints: You cannot use the virtual modifier with the static, private, abstract or override modifiers.

Example:

    class MyParentClass
    {
        public virtual string MyName { get; set; }

        private int number;
        public virtual int Number
        {
            get { return number; }
            set { number = value; }
        }
    }

    class MyChildClass : MyParentClass
    {
        private string myName;

        public override string MyName
        {
            get { return myName; }
            set 
            {
                if (!string.IsNullOrEmpty(value))
                {
                    myName = value;
                }
                else
                {
                    myName = "Patrick";
                }
            }
        }
    }