Understanding virtual, override, and method overloading in C#
Roman Fairushyn
Senior Software Engineer | .NET Enthusiast | Tech Content Creator | Teacher in State University of Telecommunications | Talks about #azure, #csharp, #dotnet, and #programming
1. Virtual and Override
The virtual keyword in C# allows subclasses to override methods of the base class. This is critical for enabling polymorphism in object-oriented programming.
For example, consider an Animal base class with a virtual Speak method:
The Speak method can be overridden in a Dog class:
This override means that if you create an instance of Dog and call its Speak method, you'll get "The dog barks" instead of "The animal makes a sound".
But if you call the Speak method through a variable of type Animal, you still get the overridden version:
This is called polymorphism: the same method call can have different effects depending on the type of object it's called on.
2. Method Overloading
Method overloading in C# allows a class to have multiple methods with the same name, but with different parameters. Overloaded methods can have different numbers of parameters, or parameters of different types.
For instance, let's consider a Print method which could print integers or strings:
领英推荐
You can call these methods like so:
Method overloading is useful because it allows you to provide the same functionality for different types or quantities of arguments, making your code easier to read and use.
3. Implementing Interface Methods
Interfaces in C# define a contract that classes can implement. An interface can declare any number of methods, properties, events, or indexers. When a class implements an interface, it commits to providing an implementation for each of these members.
Let's create an IFlyable interface and a Bird class that implements it:
Now we can create a?Bird?instance and call its?Fly?method:
This example shows that a?Bird?can fly because it implements the?IFlyable?interface. If we had other classes like?Airplane?or?Superhero?that could also fly, they could implement?IFlyable?as well. This is an important principle of OOP known as "programming to an interface, not an implementation".
Conclusion
Understanding these concepts is key to properly utilizing C# in an object-oriented manner. They enable you to create more flexible and maintainable code, and are thus important topics in technical interviews.
There is also implementation of interface methods to mention