Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi,

I am new to .net so please let me clear my doubt .
i wanted to know the scenarios where i have to declare my method as virtual.otherwise it will not work.
Posted
Comments
Sushil Mate 8-Aug-13 5:26am    
when you wanted to override in the derived class. more precise, Virtual method might have default implementation but you can change me if you need in the derived.

Hi,

Define the Virtual methods only in the case if the methods are to be overridden in the derived classes as per their behavior. For an example the shape class can have Draw method. The Circle, Rectangle classes which derived from the Shape class can override the Draw method.

Regards,
Raghu
 
Share this answer
 
In polymorphism we have method overloading and method overriding.

Method overloading is the process of creating new method with same name but different signature.

Method overriding is the process of creating new method with same name and same signature but in a derived class.

In method overriding you have to declare a method with virtual keyword in base class which indicates that it is going to be overridden. In derived class the overriding method should use override keyword.
 
Share this answer
 
v3
C#
class Class1
{
    public virtual int GetNumber()
    {
        return 1;
    }
}

C#
class Class2 : Class1
{
    public override int GetNumber()
    {
        int i = base.GetNumber();
        return i + 1;
    }
}

C#
private void button1_Click(object sender, EventArgs e)
{
    Class1 class1 = new Class1();
    Class2 class2 = new Class2();

    MessageBox.Show("GetNumber() from Class1: " + class1.GetNumber());
    MessageBox.Show("GetNumber() from Class2: " + class2.GetNumber());
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900