csharp

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:

Interface <name>

{

……

}

Implementing Syntax of C# interface:

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):

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):

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):

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:

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:

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:

C# interface

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:

IB ref = a;

The IB interface methods, and only these, can now be called via ref:

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:

 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:

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:

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:

class Base

{

.....

}

Interface IB

{

.....

}

class Derived: Base, IB

{

.....

}

An object of the Base class is created by:

Base b = new Base();

 

An object of the Derived class can be created by:

Derived d1 = new Derived();

but also by (since an object of a derived class is also an object of its base class):

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:

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):

IB refB = (IB) d2;

refB.f (); // no problem since d2 is actually a Derived



But what if you write:

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:

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):

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.

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:

C# interface

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button