Versioning with the Override and New Keywords - C# (2024)

  • Article

The C# language is designed so that versioning between base and derived classes in different libraries can evolve and maintain backward compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is completely supported by C# and does not lead to unexpected behavior. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that hides a similarly named inherited method.

In C#, derived classes can contain methods with the same name as base class methods.

By default, C# methods are not virtual. If a method is declared as virtual, any class inheriting the method can implement its own version. To make a method virtual, the virtual modifier is used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class.

To demonstrate this in practice, assume for a moment that Company A has created a class named GraphicsClass, which your program uses. The following is GraphicsClass:

class GraphicsClass{ public virtual void DrawLine() { } public virtual void DrawPoint() { }}

Your company uses this class, and you use it to derive your own class, adding a new method:

class YourDerivedGraphicsClass : GraphicsClass{ public void DrawRectangle() { }}

Your application is used without problems, until Company A releases a new version of GraphicsClass, which resembles the following code:

class GraphicsClass{ public virtual void DrawLine() { } public virtual void DrawPoint() { } public virtual void DrawRectangle() { }}

The new version of GraphicsClass now contains a method named DrawRectangle. Initially, nothing occurs. The new version is still binary compatible with the old version. Any software that you have deployed will continue to work, even if the new class is installed on those computer systems. Any existing calls to the method DrawRectangle will continue to reference your version, in your derived class.

However, as soon as you recompile your application by using the new version of GraphicsClass, you will receive a warning from the compiler, CS0108. This warning informs you that you have to consider how you want your DrawRectangle method to behave in your application.

If you want your method to override the new base class method, use the override keyword:

class YourDerivedGraphicsClass : GraphicsClass{ public override void DrawRectangle() { }}

The override keyword makes sure that any objects derived from YourDerivedGraphicsClass will use the derived class version of DrawRectangle. Objects derived from YourDerivedGraphicsClass can still access the base class version of DrawRectangle by using the base keyword:

base.DrawRectangle();

If you do not want your method to override the new base class method, the following considerations apply. To avoid confusion between the two methods, you can rename your method. This can be time-consuming and error-prone, and just not practical in some cases. However, if your project is relatively small, you can use Visual Studio's Refactoring options to rename the method. For more information, see Refactoring Classes and Types (Class Designer).

Alternatively, you can prevent the warning by using the keyword new in your derived class definition:

class YourDerivedGraphicsClass : GraphicsClass{ public new void DrawRectangle() { }}

Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior.

Override and Method Selection

When a method is named on a class, the C# compiler selects the best method to call if more than one method is compatible with the call, such as when there are two methods with the same name, and parameters that are compatible with the parameter passed. The following methods would be compatible:

public class Derived : Base{ public override void DoWork(int param) { } public void DoWork(double param) { }}

When DoWork is called on an instance of Derived, the C# compiler will first try to make the call compatible with the versions of DoWork declared originally on Derived. Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived, it will try to match the call to an overridden method with the same name and compatible parameters. For example:

int val = 5;Derived d = new Derived();d.DoWork(val); // Calls DoWork(double).

Because the variable val can be converted to a double implicitly, the C# compiler calls DoWork(double) instead of DoWork(int). There are two ways to avoid this. First, avoid declaring new methods with the same name as virtual methods. Second, you can instruct the C# compiler to call the virtual method by making it search the base class method list by casting the instance of Derived to Base. Because the method is virtual, the implementation of DoWork(int) on Derived will be called. For example:

((Base)d).DoWork(val); // Calls DoWork(int) on Derived.

For more examples of new and override, see Knowing When to Use Override and New Keywords.

See also

  • The C# type system
  • Methods
  • Inheritance
Versioning with the Override and New Keywords - C# (2024)
Top Articles
The Future is Bright for Star Wars™: The Old Republic™
Cinemark hiring Theatre Team Member in Towson, MD | LinkedIn
Mickey Moniak Walk Up Song
Riverrun Rv Park Middletown Photos
I Make $36,000 a Year, How Much House Can I Afford | SoFi
Cottonwood Vet Ottawa Ks
Nyu Paralegal Program
Ixl Elmoreco.com
Don Wallence Auto Sales Vehicles
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
Scentsy Dashboard Log In
Progressbook Brunswick
Valentina Gonzalez Leaked Videos And Images - EroThots
Assets | HIVO Support
Pittsburgh Ultra Advanced Stain And Sealant Color Chart
Lax Arrivals Volaris
Wilmot Science Training Program for Deaf High School Students Expands Across the U.S.
Letter F Logos - 178+ Best Letter F Logo Ideas. Free Letter F Logo Maker. | 99designs
Haunted Mansion Showtimes Near Millstone 14
Bank Of America Financial Center Irvington Photos
U Arizona Phonebook
Jet Ski Rental Conneaut Lake Pa
Closest Bj Near Me
Curver wasmanden kopen? | Lage prijs
Catherine Christiane Cruz
John Chiv Words Worth
Home
Walgreens Bunce Rd
Airline Reception Meaning
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
Foodsmart Jonesboro Ar Weekly Ad
Cowboy Pozisyon
Great ATV Riding Tips for Beginners
Joann Fabrics Lexington Sc
Calculator Souo
Shaman's Path Puzzle
Babbychula
#scandalous stars | astrognossienne
Why The Boogeyman Is Rated PG-13
Etowah County Sheriff Dept
Hotels Near New Life Plastic Surgery
Bbc Gahuzamiryango Live
Albertville Memorial Funeral Home Obituaries
Oriellys Tooele
Skip The Games Grand Rapids Mi
Kerry Cassidy Portal
2700 Yen To Usd
Love Words Starting with P (With Definition)
Chr Pop Pulse
Mikayla Campinos Alive Or Dead
Arnold Swansinger Family
Island Vibes Cafe Exeter Nh
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 6098

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.