Inheriting an interface p.1

  1. What actually the C# compiler does when I implement an interface.
  2. How to manage with sealed limitations.

When I implement an interface the C# compiler implicitly mark methods as virtual and sealed. In this case a derived class can’t override the methods. The C# compiler requires that methods are marked as public.  If I explicitly mark a method as virtual the C# compiler marks the method as virtual (leaves it unsealed).

To manage with sealed limitations derived class can makes its own interface implementation. 

Example 1:

using System;


namespace Interfaces


    public delegate void MyEventHandler(int param);


    internal interface IBaseInterface


        void Method();

        int Property { set; get; }

        int this[int index] { set; get; }

        event MyEventHandler MyEvent;



    //All methods that implement an interface must be marked as public

    public class BaseInterfaceClass : IBaseInterface


        public void Method() { Console.WriteLine("Method of base interface"); }


        private int _propertyField = 0;


        public int Property


            set { _propertyField = value; }

            get { return _propertyField; }



        private int _indexerField = 0;


        public int this[int index]


            set { _indexerField = index; }

            get { return _indexerField; }



        public event MyEventHandler MyEvent;



    class Program


        static void Main(string[] args)


            BaseInterfaceClass b = new BaseInterfaceClass();



            DerivedInterfaceClass d = new DerivedInterfaceClass();



            IBaseInterface bi = new BaseInterfaceClass();



            IBaseInterface di = new DerivedInterfaceClass();








Example 2:


    public class DerivedInterfaceClass : BaseInterfaceClass


        public new void Method() { Console.WriteLine("Method of derived interface"); }





    Method of base interface

    Method of derived interface

    Method of base interface

    Method of base interface



 As we can see from the example 2 the di.Method()  calls the method of the base class, because the C# compiler implicitly makes it sealed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s