CSharp - Partially implement interface

Introduction

If the class cannot implement all of methods from interface, it will mark itself abstract.

In the following code, our interface has two methods.

The class is implementing only one. So, the class itself becomes abstract.

interface IMyInterface
{
        void Show1();
        void Show2();
}
//MyClass becomes abstract. It has not implemented Show2() of IMyInterface
abstract class MyClass2 : IMyInterface
{
        public void Show1()
        {
            Console.WriteLine("MyClass.Show1() is implemented.");
        }
        public abstract void Show2();
}

Analysis

A class needs to implement all the methods defined in the interface; otherwise, it will be an abstract class.

Demo

using System;

interface IMyInterface
{
    void Show1();
    void Show2();
}
// MyClass becomes abstract. It has not implemented Show2() of IMyInterface
abstract class MyClass2 : IMyInterface
{
    public void Show1()
    {/*  ww  w  . j a va 2  s  .c o  m*/
        Console.WriteLine("MyClass.Show1() is implemented.");
    }
    public abstract void Show2();
}
class ChildClass : MyClass2
{
    public override void Show2()
    {
        Console.WriteLine("Child is completing -Show2() .");
    }
}

class Program
{
    static void Main(string[] args)
    {
        //MyClass is abstract now
        //MyClass myClassOb = new MyClass();
        MyClass2 myOb = new ChildClass();
        myOb.Show1();
        myOb.Show2();
    }
}

Result

Related Topic