Sunday, January 20, 2013

Virtual keyword declaration for a method or property?

Virtual keyword

Virtual” keyword is used in a base class with method or property to override in derive class i.e. the “Virtual” method or property can be overridden in derive class. 

Virtual Example

    // Base class 
    class Parent
    {
        public virtual int Calculation(int i, int j)
        {
            return i * j;
        }

    }

    // Derive class
    class child : Parent
    {
        public override int Calculation(int i, int j)
        {
            return i / j;
        }
    }

        static void Main(string[] args)
        {
            Parent obj = new Parent();
            int i = obj.Calculation(20, 10);
            Console.WriteLine(i);

            Parent obj1 = new child();
            int j = obj1.Calculation(20, 10);
            Console.WriteLine(j);
        }

Output

200
2

No comments:

Post a Comment