Friday, January 28, 2011

Virtual Methods in C-Sharp


The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:


A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.


When a virtual method is invoked, the run-time type of the object is checked for an overriding member in derived classes if not it will use base method.
By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the static, abstract, private or override modifiers.

It is an error to use the virtual modifier on a static property.

Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax. The main difference between abstract method and virtual method is abstract method doesn't have declaration where as virtual method does.

Here is the example
class Fruits
    {
        public virtual void Name()
        {
            // its a generic here it can be any fruit like Apple,Banana,Mango etc.
            Console.WriteLine("Iam a fruit");
        }
       
    }
    class Apple : Fruits
    {
        public override void Name()
        {
            //base.Name(); here using this you can directly use base method
            // or you can override it.
            Console.WriteLine("Iam a Apple");
        }
    }
    class Mango : Fruits
    {
        public override void Name()
        {
            Console.WriteLine("Iam a Mango");
        }
    }
    class Banana : Fruits
    {
        public override void Name()
        {
            Console.WriteLine("Iam a Banana");
        }
    }

Importance of Override Keyword
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. For information on inheritance, see Inheritance.


You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract.


An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
You cannot use the modifiers new, static, virtual, or abstract to modify an override method.
An overriding property declaration must specify the exact same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override.

Microsoft Visual C# 2010 Step by Step

No comments:

Post a Comment