Jitesh Byahut 10/10/2014 2288

Virtual keyword In C#

Virtual keyword in C# use to modify any method, property, indexer or event. When you define any method then that method by default is non-virtual method and you cannot modify that method, so if you want to modify any method then you have to specify virtual keyword with method after that you can modify that method in derived class.

When you define virtual method then at run time, its search most override method in derived class and call that one and if not overridden then call virtual method. If you override a method then at run time, most derived method is called.

You cannot use abstract, static, override or private keyword with virtual keyword.

Define virtual method

You can define virtual method that override in derived class and both must have same signature.

class BaseClass

{

    // virtual method

    public virtual void DisplayMessage()

    {

        Console.WriteLine("virtual method");

    }

}

class DerivedClass : VirtualClass

{

    // override virtual method

    public override void DisplayMessage()

    {

        Console.WriteLine("override a virtual method");

    }

}

Define virtual property

Here We are defining a virtual property MovieRating of type integer inside base class and that override in derived class. We provide logics in override implementation.

Property MovieRating provides user to give their ratting on movie. Here max movie ratting is 5, but suppose any user give more than 5 rating, then by default its showing 5 star rating.

class TestClass

{

    // virtual property

    public virtual int MovieRating { get; set; }

}

   

 

class Program : TestClass

{

    // override property

    public override int MovieRating

    {

        get

        {

            return base.MovieRating;

        }

        set

        {

            if (value >5 )

            {

                value = 5;

            }

            base.MovieRating = value;

        }

    }    

}


Please give your feedback for improving this page