C# Interface with Programming Examples
C# Interfaces
C# Interface:- C# knows no multiple inheritances in classes. Even with abstract ones, there are no multiple inheritances for classes. C# interfaces are on the other hand C# interfaces that only contain prototypes of methods. They serve to standardize programs. Multiple inheritances are allowed.
Declaration Syntax of C# interface:
1 2 3 4 5 6 7 |
Interface <name> { …… } |
Implementing Syntax of C# interface:
1 |
Class class_name : interface_name |
C# interfaces are often an alternative to abstract classes. In the C# interface, we only find the signature of these methods; we cannot find any code (which is only possible in abstract classes). We also cannot find a qualifier like public, private or protected because it’s up to the class implementing the interface to decide. If a function of the C# interface (of which only the signature is given) accepts one or more arguments, it is necessary oddly enough to give a name to these arguments. Declare the IB interface (the custom is to start the name of an interface with I):
1 2 3 4 5 6 7 |
Interface IB{ void f1 (int a); // don't forget to give the argument a name void f2 (); } |
Classes that implement the IB interface will need to implement the functions f1 and f2. Other said, they should contain the body of these functions and it is up to you to write these instructions in classes implementing IB. A C# interface can only contain signatures, it cannot contain any function body or field (unlike abstract classes which can contain fields and function implementations). A C# interface can contain definitions of properties or indexers. For example (an indexer on an integer must be fully implemented in any class implementing the IX interface):
1 2 3 4 5 6 7 |
Interface IX { object this [int n] {get; Â set;} } |
A C# interface can be derived from another interface. We say that a C# interface can “implement” another interface, even if it is not strictly speaking an implementation. The C# interface derivative then includes its own methods as well as those of the base interface (without forgetting that these are only signatures). Unlike classes, for which the derivation multiple is not allowed, an C# interface can derive from several interfaces: it suffices to separate by commas the names of the various basic interfaces. A class can also implement several interfaces. As a reminder, a class can only derive from a single class.
A class implementing an interface
A class indicates that it implements an interface (or several interfaces) as follows (little difference in syntax compared to class inheritance):
1 2 3 4 5 6 7 8 9 10 11 |
class X: IB Â // class X implementing the IB interface { ..... // fields and methods specific to class X void f1 (int a) {.....} void f2 () {.....} } |
or, if the class implements multiple C# interfaces:
1 2 3 4 5 6 7 8 9 10 11 |
class X: IB, IC { ..... // fields and methods specific to X void f1 (int a) {.....} // development of methods from IB void g1 () {.....} // development of methods from IC } |
In the following program, class A implements interface IB (the order of appearance of C# interfaces, classes and Main is irrelevant):
C# interface implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceExample {    interface IB    {        void f();        void g();    }    class A : IB    {        public void f() { Console.WriteLine("f of A"); }        public void g() { Console.WriteLine("g of A"); }    }    class Program    {        static void Main(string[] args)        {            A a = new A();            a.f();            a.g();            Console.ReadKey();        }    } } |
Output:
Reference to an interface:
In the above example, a denotes a reference to object A. As class A implements the interface IB, a can be converted to a reference (here called ref) to the interface IB:
1 |
IB ref = a; |
The IB interface methods, and only these, can now be called via ref:
1 |
ref.f(); |
A class implementing several interfaces:
If class A implements the interfaces IB and IC, it is possible that functions of IB carry the same name as functions of IC:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
 Interface IB { void f (); void g (); } interface IC { double f (int a); void h(); } |
If class A implements the interfaces IB and IC, A must implement f of IB and f of IC. There is ambiguity since we find f in both IB and IC. Regardless of the signature (type and number of arguments) of these functions, there is ambiguity as long as two names are identical. To solve the problem, class A must specify that it implements f of A and f of B. These two functions can only be called via interface references:
1 2 3 4 5 6 7 8 9 |
class A: IB, IC { void IB.f () {.....} double IC.f (int a) {.....} } |
To execute these functions applied to an object of class A, we must write:
1 2 3 4 5 6 7 8 9 |
A a = new A(); IB ref1 = a; Ref1.f (); // execution of f of IB applied to a IC ref2 = a; double d = ref2.f (5); // execution of f of IC applied to a |
How do you determine that a class implements an interface?
Consider a base class called Base (base is a reserved word, not Base), an IB interface, and a Derived class derived from Base and implementing IB interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Base { ..... } Interface IB { ..... } class Derived: Base, IB { ..... } |
An object of the Base class is created by:
1 |
Base b = new Base(); |
An object of the Derived class can be created by:
1 |
Derived d1 = new Derived(); |
but also by (since an object of a derived class is also an object of its base class):
1 |
Base d2 = new Derived(); // d2 is in fact an object of the class Derived |
To determine if an object of the Base class (b or d2) implements the IB interface (this is the case for d2 but not for b), we can write:
1 |
if (d2 is IB) ..... // d2 effectively implements IB |
We can therefore write (the cast is necessary because d2 is officially an object of the Base class which does not implement IB):
1 2 3 |
IB refB = (IB) d2; refB.f (); // no problem since d2 is actually a Derived |
But what if you write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Base [] arrBase = new Base [2]; arrBase [0] = b; arrBase [1] = d2; foreach (Base bo in tabBase) { refB = (IB) bo; refB.f (); } |
Each cell in tabBase is a Base object or an object of a class derived from Base (Derived in this case). For cells that contain a Derived object, calling f via refB is correct. On the other hand, for cells actually containing a Base object, this constitutes a serious error, with the termination of the program if the error is not caught in a try/catch. The compiler accepts the syntax because the determination of the actual content of bo can only be done at the time of running the program. A first solution is to test the contents of bo:
1 2 3 4 5 6 7 8 9 10 11 |
foreach (Base bo in tabBase) if (bo is IB) { refB = (IB) bo; rerB.f (); } |
Another solution is to try a conversion (as operator) and check the result of the conversion (bo as IB gives null as a result when bo does not implement the IB interface):
1 2 3 4 5 6 7 8 9 |
foreach (Base bo in tabBase) { refB = bo as IB; if (refB! = null) refB.f(); } |
C# Interface Programming Examples:
how to implement an interface in c#:
So in the example below the class Rectangle from the interfaces Corner and Sides be derived. Rectangle must implement all inherited methods. This ensures that the methods provided by the C# interfaces are.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterfaceExample {  class Program    {        public Program()        {            Rectangle r = new Rectangle(15, 30, 400, 300);            Console.WriteLine("{0}\t {1}\t{2}\t{3}", r.getx(), r.gety(), r.b, r.h);        }        static void Main(string[] args)        {            Program data = new Program();            Console.ReadKey();        }        interface corner        {            int getx();            int gety();        }        interface sides        {            int getb();            int geth();        }        class Rectangle : corner, sides        {            public int x, y, b, h;            public Rectangle(int x, int y, int b, int h)            {                this.x = x;                this.y = y;                this.b = b;                this.h = h;            }            public int getx()            {                return x;            }            public int gety()            {                return y;            }            public int getb()            {                return b;            }            public int geth()            {                return h;            }        }    } } |
output: