C#. Interfaces




Interfaces



Search other websites:

1. The purpose of the interfaces. Features of using interfaces in C#

An interface defines a number of methods (properties, indexers, events) that must be implemented in a class that inherits (implements) this interface. Interfaces are used to indicate to classes what exactly needs to be implemented in these classes. You need to implement methods (properties, indexers, events).

Thus, the interface describes functionality without a specific implementation. In other words, an interface defines a specification but not an implementation.

Using interfaces is effective in cases where you need to create an alternative to multiple inheritance. Any class can inherit several interfaces. Moreover, all methods of inherited interfaces must be implemented in the class.

A structure, like a class, can implement any number of interfaces.

Interfaces Features:

  • you cannot enter the implementation of its elements in the interface;
  • you can not create an instance of the interface;
  • you can create a reference to the interface;
  • there can be no constructors in an interface;
  • the interface cannot contain fields;
  • the operator cannot be overloaded in the interface;
  • all interface methods are declared public by default.

When using interfaces in derived classes:

  • it is forbidden to change the access modifier for a method when it is implemented;
  • it is impossible to declare interface methods as virtual;
  • It is forbidden to declare interface methods with the static keyword (as static).

   

2. What is the difference between interfaces and abstract classes?

In the C# programming language, there are the following differences between interfaces and abstract classes:

  1. It is forbidden to register the implementation of its members in the interface. In an abstract class, some members may have an implementation. In other words, an interface is the same abstract class in which all methods are abstract.
  2. It is forbidden to describe fields (variables, objects) in an interface; in an abstract class it is possible.
  3. It is forbidden to declare overloaded operators in an interface. In an abstract class, under certain conditions, it is allowed to declare overloaded operators.
  4. An interface cannot contain a constructor. A constructor can be declared in an abstract class.
  5. Any class can be inherited from several interfaces. Moreover, any class can be inherited from only one abstract class (and no more).
  6. It is forbidden to declare static members in an interface (with the static keyword). It is allowed to declare static members in an abstract class.
  7. In an interface, all members are considered public, and therefore no access modifiers are used in an interface. In an abstract class, elements can be declared with any access modifier (private, protected, public).

   

3. How many classes can have an implementation of the interface methods?

If the interface is defined, it can be implemented in any number of classes.

   

4. How many interfaces can be implemented in one class?

In a class of any number of interfaces can be implemented.

   

5. What is the general form of the description of the interface?

Interfaces are declared using the keyword “interface“. The general form of the description of the interface, which defines the methods is the following:

interface name
{
    return_type1 method1(parameters1);
    return_type2 method2(parameters2);
    // ...
    return_typeN methodN(parametersN);
}

where

  • name – the name of interface;
  • method1, method2, …, methodN – names of interface methods;
  • return_type1, return_type2, …, return_typeN – the types, which are returned by interface methods;
  • parameters1, parameters2, …, parametersN – lists of parameters of interface methods.

Besides methods you can specify the properties, events and indexers in the interfaces.

   

6. What elements of programming language you can specify in the interfaces?

You can specify in the interfaces:

  • methods;
  • properties;
  • indexers;
  • events.

   



7. What is the general form of implementation of the interface in the class?

The general form of implementation of the interface in the class is following:

class class_name : interface_name
{
    // body of the class
    ...
}

where interface_name – the name of the interface. The class must implement all interface methods.

   

8. What is the general form for a class, that implements multiple interfaces?

A class can implement multiple interfaces. In this case, all the interfaces are defined by a list of comma-separated.

The general form for a class, that implements multiple interfaces:

class class_name : interface_name1, interface_name2, ..., interface_nameN
{
    // body of the class
    ...
}

where interface_name1, interface_name2, …, interface_nameN – interface names, which must implement the class. The class must implement all methods of all interfaces.

   

9. Example the interface declaring and declaring the class that inherits this interface.

In this example, the interface is named IMyInterface. It is recommended add the prefix “I” to the name of the interface in accordance with common practice.

The interface is declared as “public“.

public interface IMyInterface
{
    int MyGetInt(); // a method that returns the number of type int
    double MyGetPi(); // a method that returns Pi
    int MySquare(int x); // method that returns x square
    double MySqrt(double x); // the method that returns the square root of x
}

In the example, the definition of four methods in the interface, is declared. These methods must be specified in all classes, that define these interfaces. These are methods: MyGetInt(), MyGetPi(), MySquare(), MySqrt().

Example of class description which uses this interface.

public class MyClass : IMyInterface
{
    // "public" access modifier
    public int MyGetInt()
    {
        return 25;
    }

    public double MyGetPi()
    {
        return Math.PI;
    }

    public int MySquare(int x)
    {
        return (int)(x * x);
    }

    public double MySqrt(double x)
    {
        return (double)Math.Sqrt(x);
    }
}

All of the methods defined in the class must have access type public. If you install a different type of access (private or protected), then Visual Studio will issue the following message:

"MyClass does not implement interface member MyFun() because it is not public."

where MyFun () – the name of the function, which is implemented in a class with “private” or “protected” access modifier.

This is due to the fact that these methods are implicitly considered open (public) in the interface. Therefore, their implementation should be open.

   

10. Example of declaring two interfaces and a class, that implements the methods of these interfaces.

In the following example, declared two interfaces with the names MyInterface and MyInterface2. The first interface includes 4 methods. Second interface includes 1 method.

Class MyClass also is declared, that uses these two interfaces. The class must implement all methods of both interfaces, ie in the amount of 5 methods.

public interface IMyInterface
{
    int MyGetInt(); // method that returns integer
    double MyGetPi(); // method that returns Pi
    int MySquare(int x); // method that returns x square
    double MySqrt(double x); // method that returns the square root of x
}

public interface IMyInterface2
{
    double MySqrt2(double x); // square root of x
}

public class MyClass : IMyInterface, IMyInterface2
{
    // the methods of the interface MyInterface
    public int MyGetInt()
    {
        return 25;
    }

    public double MyGetPi()
    {
        return Math.PI;
    }

    public int MySquare(int x)
    {
        return (int)(x * x);
    }

    public double MySqrt(double x)
    {
        return (double)Math.Sqrt(x);
    }

    // the method of interface MyInterface2
    public double MySqrt2(double x)
    {
        return (double)Math.Sqrt(x);
    }
}

   

11. Example of a reference to the interface to access the class method.

In C# is allowed to define links to the interface. If you describe a variable-reference to the interface, you can use it to call the methods of a class that uses this interface.

Example.

public interface IMyInterface
{
    double MyGetPi(); // method that returns Pi
}

class MyClass : IMyInterface
{
    // methods of interface MyInterface
    public double MyGetPi()
    {
        return Math.PI;
    }
}

// call from the program code
private void button1_Click(object sender, EventArgs e)
{
    MyClass mc = new MyClass(); // create a class object
    IMyInterface mi; // reference to the interface
    double d;

    mi = mc; // mi refers to the object of mc class
    d = mi.MyGetPi(); // d = 3.14159265358979
    label1.Text = d.ToString();
}

This example creates an object (instance) of the class MyClass named mc. Then, the reference to the interface IMyInterface with name mi is declared.

The string

mi=mc;

leads to the fact that the reference mi points to the object mc of class. Thus, through a link “mi” can have access to the methods of MyClass, because the class MyClass implements methods IMyInterface interface.

With a reference to the interface you can have access to the class methods that implement the techniques described in this interface.

   

12. How does the interface describes a property?

The property is described in the interface without a body. The general form of the interface property definition is following:

type property_name
{
    get;
    set;
}

If the property is read-only, then you need to use only one accessor get.

If the property is intended for saving, then you need to use the only one accessor “set“.

Example. The declaration of interface and class. Class returns property MyPi.

public interface IMyInterface
{
    double MyGetPi(); // method that returns Pi

    // property that returns Pi
    double MyPi
    {
        get;
    }
}

class MyClass : IMyInterface
{
    // method
    public double MyGetPi()
    {
        return Math.PI;
    }

    // specify the property in the class
    public double MyPi
    {
        get
        {
            return Math.PI;
        }
    }
}

// Using of the interface property in the event handler of clicking on the button
private void button1_Click(object sender, EventArgs e)
{
    MyClass mc = new MyClass(); // create an object "mc" of the class
    label1.Text = mc.MyPi.ToString(); // reading the property
}

   

13. An example of an interface, which describes the indexer.

The general form of the interface indexer declaration is as follows:

type this[int index]
{
    get;
    set;
}

Example of use of interface indexer, which reads an element from an array consisting of 5 elements of type double.

public interface IMyInterface
{
    // interface indexer
    double this[int index]
    {
        get;
    }
}

class MyClass : IMyInterface
{
    double[] mas = { 3, 2.9, 0.5, 7, 8.3 };

    public double this[int index]
    {
        get
        {
            return mas[index];
        }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MyClass mc = new MyClass(); // create the object of class mc
    double d;
    d = mc[2]; // d = 0.5
    label1.Text = d.ToString();
}

   

14. Which elements of the C# programming language can not be defined in interfaces?

Interfaces can not define:

  • data members;
  • constructors;
  • destructors;
  • operator methods.

   

15. How does the interface inheritances?

The interface can inherit other interface. The syntax of interfaces inheritance is the same as in the classes.

The general form of inheritance the interface is following:

interface interface_name : interface_name1, interface_name2, ..., interface_nameN
{
    // Methods, properties, indexers, and events
    ...
}

where interface_name – the name of interface, which inherits other interfaces;

interface_name1, interface_name2, …, interface_nameN – the names of the ancestors of interfaces.

Example. In this example, MyClass class uses an interface that inherits another interface. The class must implement all methods (properties, indexers, events) of interfaces MyInterface1 and MyInterface2 interface.

// base interface
interface MyInterface1
{
    void Int1_Meth();
}

// interface that inherits another interface
interface MyInterface2 : MyInterface1
{
    void Int2_Meth();
}

// class that uses the IMyInterface2
class MyClass : MyInterface2
{
    // the implementation of interface method MyInterface1
    public void Int1_Meth()
    {
        // body of the method
        // ...
        return;
    }

    // the implementation of interface method MyInterface2
    public void Int2_Meth()
    {
        // body of the method
        // ...
        return;
    }
}

   

16. What is the explicit interface implementation?

If the front of the name of the method (property, indexer, event) is the interface name through a separator ‘ . ‘ (dot), then it is called an explicit interface member implementation.

An example of explicit implementation.

// base interface
interface MyInterface1
{
    void Method();
}

// class that implements MyInterface1
class MyClass : MyInterface1
{
    // explicit implementation of the method of MyInterface1 interface
    void MyInterface1.Method() // specified the interface name
    {
        // body of the method
        // ...
        return;
    }
}

   

17. When it is advisable to use an explicit interface member implementation? Examples.

Explicit interface member implementation is applied in the following cases:

  • if you want the interface method has been accessible over the interface reference, and not by a class object that implements this interface. In this case, the interface method is not open (public) member of the class (see Example 1);
  • if in the class two interfaces are implemented, in which the methods have the same name and signature (see. Example 2).

Example 1. Explicit implementation of interface method. At the interface reference the method is accessible and it is unavailable for the class object.

// Interface
interface MyInterface1
{
    void Method();
}

// class, that calls the interface
class MyClass : MyInterface1
{
    // the explicit implementation of the interface method MyInterface1
    // access modifier, must be absent
    void MyInterface1.Method() // specified the interface name
    {
        // body of the method
        // ...
        return;
    }

    void InternalMethod()
    {
        MyInterface1 mi = this; // mi - interface reference
        mi.Method(); // it works!

        MyClass mc = this; // mc - the object of MyClass class
    
        // mc.Method() - can not call - the method is not open to the object
    }
}

Example 2. There are two interfaces MyInterface1 and MyInterface2. Each of them has methods with the same names and signatures. In this case, Method() method does not return parameters (void). Using the explicitly implementation, class recognizes these methods.

// interface #1
interface MyInterface1
{
    void Method();
}

// interface #2
interface MyInterface2
{
    void Method();
}

// A class that uses two interfaces
class MyClass : MyInterface1, MyInterface2
{
    // explicit implementation - access modifier (public) must be absent
    // method of MyInterface1 interface
    void MyInterface1.Method()
    {
        // body of the method
        // ...
        return;
    }

    // method of MyInterface2 interface
    void MyInterface2.Method()
    {
        // body of the method
        // ...
        return;
    }
}

   

18. In what cases it is better to use interface and in what abstract class?

The interface should be used in cases where some of the concepts should be described in terms of the functionality, without specifying the implementation details.

An abstract class should be used when still need to specify some of the details of implementation.


Related topic