+1 vote
in C Sharp by
What is an Interface in C#?

1 Answer

0 votes
by
An Interface is similar to an Abstract class and it also cannot be instantiated.

•      Cannot be instantiated i.e. object cannot be created using the new keyword.

•      Can contain only declaration of Members and not definition.

•      Members are simply declared and are defined in the classes deriving the Interface.

•      Members are defined without using the override keyword.

•      Cannot contain Access modifiers i.e. Members cannot be public, private, etc.

•      The derived member can only be public.

•      Does support Multiple Inheritance.

Example:

public interface A

{

    void Fun1();

    void Fun2();

}

public class B : A

{

    public void Fun1()

    {

    }

    //Error: 'B' does not implement interface member 'A.Fun2()'

    //'B.Fun2()' cannot implement an interface member because it is not public

    private void Fun2()

    {

    }

}

public class C

{

    public static void Fun3()

    {

        //Compiler Error: Cannot create an instance of the abstract class or interface 'A'

        A a = new A();

 

        //Valid

        B b = new B();

        b.Fun1();

 

        //Invalid

        b.Fun2();

    }

}

Related questions

0 votes
+1 vote
+1 vote
0 votes
asked Oct 18, 2019 in C Sharp by Robin
0 votes
0 votes
0 votes
asked Aug 17, 2023 in C Sharp by GeorgeBell
...