virtual Summary The virtual modifier is used to declare a method as a virtual method that can be overridden by derived classes using the 'override' keyword. Syntax virtual member Parameters member The member to make 'virtual'. Description The virtual modifier is used to declare a method or property as a virtual method or property, respectively. Virtual methods can be overridden using the override or final modifier. By default, methods are non-virtual and are resolved at compile time. If a derived class has a method with the same name as its base class, this is known as shadowing (or method hiding) and gets resolved at compile time. However, virtual methods are resolved at runtime. At runtime, when a virtual method is called, the runtime type of the invoking object is examined, and the overridden method of the most derived class is called. If no overridden methods are available, the original virtual method is invoked. A method cannot be overridden if: It is not virtual or abstract It is static It has a different access modifier It has a different return type, parameter type, parameter order, or method signature Examples Iterating Array of Objects and Calling Overridden Functions 123456789101112131415161718192021222324252627282930313233343536373839404142434445import System; class Shape{ public virtual double area() { return 0; }} class Rectangle : Shape{ private int length, width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public override double area() { return length * width; }} class Triangle : Shape{ private int base, height; public Triangle(int base, int height) { this.base = base; this.height = height; } public override double area() { return (base * height) / 2; }} Shape[] shapes = [ new Rectangle(5, 5), new Triangle(3, 4) ];foreach(Shape shape in shapes) { Console.log(shape.area());} // Output:// 25// 6 See Also override final class Share HTML | BBCode | Direct Link