Search code examples
c#.net.net-coremethodsoverriding

Overriding methods in C#


I'm currently learning C# by myself after studying Java for an entire semester.

One of the features of java (or object-oriented programming in general) is the ability to override methods that are inherited into a subclass.

When I was studying this feature in C#, I tried to override a method by myself without studying the proper way to override methods in C# and it seemed like it worked.

However, upon further study, I learned that we need to use the keyword virtual when declaring the method in the superclass and override when overriding the method in the subclass.

So my question is:
What is the correct way to override methods in C#?

Additional note: I'm also wondering if the same case applies to overloading methods in C#.


Solution

  • There are two different ways to override in .net depending on if you want to provide a default implementation or not.

    • The virtual keyword does provide a default implementation.
    • The abstract keyword does only declare what it must be overriden from those classes that inherit that class. It can only be used inside abstract classes.

    There are other inheritance related keywords like:

    • The sealed keyword says that class is final, it cannot be inherited.
    • The override keyword It says that element is overriding a parent abstract or virtual element.

    Example:

    public abstract class Bank
    {
        public abstract string Country { get; } // Everything inheriting must implement it
        public virtual decimal TaxPercent { get { return 0.25; } } // Implementing it is optional
        public decimal DeclareTaxes()
        {
            decimal taxesToPay = 4000 * TaxPercent;
            return taxesToPay;
        }
    }
    
    public sealed class BahamasBank: Bank
    {
        public override string Country { get { return "Bahamas"; }
        public override TaxPercent { get { return 0.0; } } // Bahamas is different from most countries in tax related stuff
    }
    
    public sealed class CanadaBank: Bank
    {
        public override string Country { get { return "Canada"; }
    }