SoFunction
Updated on 2025-03-07

Introduction to override of C# keyword rewriting

1. Introduction

override means rewrite. It rewrites the methods in the parent class in the subclass. The function characteristics of the two functions (function names, parameter types and numbers) are the same. They are used to expand or modify the abstract or virtual implementation of inherited methods, properties, indexers or events, and provide new implementations of members inherited from the base class. The method rewritten by override declaration is called the base method.

2. Rewrite abstract methods

    class Program
    {
        public abstract class A
        {
            public abstract void Func();
        }

        public class B : A
        {
            public override void Func()
            {
                ("B");
            }
        }

        static void Main(string[] args)
        {
            B b = new B();
        }
    }

3. Rewrite virtual methods

    class Program
    {
        public class A
        {
            public virtual void Func()
            {
                ("A");
            }
        }

        public class B : A
        {
            public override void Func()
            {
                ("B");
            }
        }
        static void Main(string[] args)
        {
            B b = new B();
            ();
        }
    }

4. Summary

1. The override base method must have the same signature as the override method.
Declares that the accessibility of the virtual method cannot be changed, and the override method and the virtual method must have the same level of access modifiers.
3. The override method cannot be modified with new, static, and virtual modifiers.
4. Rewrite attribute declarations must specify the exact same access modifier, type, and name as inherited attributes.
5. The overridden attribute must be virtual, abstract or override.
6. Non-virtual methods or static methods cannot be rewrite.
7. If there is abstract in the parent class, then the subclass method with the same name must have override; if there is a virtual method in the parent class, the subclass method with the same name may not be override.
There must be a father-son relationship.

This is all about this article about rewriting override of C# keywords. I hope it will be helpful to everyone's learning and I hope everyone will support me more.