Inheriting an interface p.2

To manage this situation:

1. We can explicitly mark a method of the base class as virtual.

 

Example 3:

   

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

    public class BaseInterfaceClass : IBaseInterface

    {

        public virtual 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;

    }

 

    public class DerivedInterfaceClass : BaseInterfaceClass

    {

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

    }

 

 

    //Output:

    Method of base interface

    Method of derived interface

    Method of base interface

    Method of derived interface

   

2. We can implement the interface of the base class in the derived class.

 

Example 4:

    //Without keyword new we get warnings like: ‘DerivedMethod’ hides inherited member ‘BaseMethod’.

    //Use the new keyword if hiding was intended.

    public class DerivedInterfaceClass : BaseInterfaceClass, IBaseInterface

    {

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

 

        private int _propertyField = 0;

 

        public new int Property

        {

            set { _propertyField = value; }

            get { return _propertyField; }

        }

 

        private int _indexerField = 0;

 

        public new int this[int index]

        {

            set { _indexerField = index; }

            get { return _indexerField; }

        }

 

        public new event MyEventHandler MyEvent;

    }

 

 

    //Output:

    Method of base interface

    Method of derived interface

    Method of base interface

    Method of derived interface

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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