Interface in C#

Introduction

An interface defines the syntactical contract that all derived classes should follow. The interface also defines the properties, methods, and events, which are known as the members of the interface. It is important to note that interfaces contain only the declaration of members. Classes and structures implement these interface members. An interface is used when you want a standard structure. A common naming convention is to prefix all interface names with a capital "I".

Why use interfaces

So if an interface implements no functionality then why should we use them? Using an interface based design concept provides loose coupling, component-based programming, easier maintainability, makes your code base more scalable and makes code reuse much more accessible because the implementation is separated from the interface. Interfaces add a plug and play like architecture into your applications. Interfaces help define a contract (agreement or blueprint, however you chose to define it), between your application and other objects. This indicates what sort of methods, properties and events are exposed by an object.

For example let's take a vehicle. All vehicles have similar items, but are different enough that we could design an interface that holds all the common items of a vehicle. Some vehicles have 2 wheels, some have 4 wheels and can even have 1 wheel. Although these are differences, they also have things in common, for example they're all movable, they all have some sort of engine, they all have doors, but each of these items may vary. So we can create an interface of a vehicle that has these properties, then we inherit from that interface to implement it.

Declaring Interfaces

You can declare interfaces using the interface keyword. The declaration of interfaces is very similar to a class declaration. Interface statements are public by default. The following code is an example of an interface declaration:

Public interface IOrderDetails
{
            //Declare an interface member
            Void UpdateCustSatus();
            Void TakeOrder();
}


You can declare only methods, functions, and properties in interfaces. You cannot declare a variable in interfaces.

Implementing Interfaces

Interfaces declare methods, which are implemented by classes. A class can inherit from a single class but can implement from multiple interfaces. The following code is an example of interface implementation:

Public interface IOrderDetails
{
//Declare an interface member
            Void UpdateCustSatus();
            Void TakeOrder();
}
Public class ItemsDetails: IOrderDetails
{
            Public void UpdateCustStatus();
            {
                      //////////////////////////////
            }
            Public void takeOrder()
            {
                       ////////////////////////////
            }
}

Interfaces can inherit members from an existing interface. The class that implements an interface must implement all the members of the interface.

Inheriting Interfaces

The following code shows how interfaces inherit from the existing interface:

public interface Validate_cust
{
            Void validate_Custname();
}
Public interface IOrderdetails: Validate_cust
{
            Void updateCustStatus();
}


A class or a structure that implements interfaces also implements the base interfaces of its inherited interface.

Type of Interfaces

The .NET Framework provides many interfaces for various purposes. Some of the commonly used interfaces are IComparable, IEquatable, IConvertible, ICloneable and IFormattable.

IComparable Interface

This interface defines a generalized comparison method that a value type or class implements to create a type-specific comparison method. With the introduction of generics in the .NET Framework 2.0 the earlier version of the IComparable interface has been enhanced to use generics. The new version is called the IComparable generic interface. The .NET Framework supports both interfaces. Both versions of the IComparable interface are implemented by types, such as the numeric and string classes, whose values can be ordered.

Method in IComparable interface

A value type or class implements the CompareTo method to create type-specific comparison methods for purposes such as string or ordering instance. The CompareTo method compares the current instance to another object of the same type.

The following code shows a sample of the CompareTo method implementation:

Public int CompareTo ( object obj )
{
            //code to implement the comparison logic
}


IEquatable interface

The iEquatable interface is a new feature of the .NET Framework 2.0. This interface applies only to generics. You can use this interface to check the equality between instances of a particular type.

Method in IEquatable interface

This interface provides a method called "Equals" method, that determines the equality of instances of the implementing type. The following code example shows the implementation of the Equal method:

Public bool Equals ( object obj )
{
            //code to check equality.
}


IConvertible interface

You use this interface to convert an object to one of the CLR types. The data type you can convert an object to include Boolean, SByte, Byte, Int16, UInt16, Int32, Uint32, Int64, UInt64, Single, Double, Decimal, DateTime, Char, and String. The methods of this interface convert the value to the equivalent data type under CTS. For example, the ToBoolean implementing type to the IConvertible interface converts the value of an instance of the implementing type to the equivalent CTS type of Boolean.

When a meaningful equivalent of the CTS type does not exist, a particular implementation of the interface method throws InvalidCastException. For example, if the IConvertible interface is implemented on a Boolean type and there is no meaningful DateTime equivalent of a Boolean type, the implementation of the ToDateTime method throws an exception.

The CLR exposes the IConvertible interface through the System.Convert class. Internally, the CLR uses the IConvertible interface in explicit interface implementations. These implementations simplify the code used to support conversion in the convert class.

The following code example shows the implementation of the IConvertiable interface:

Public class Decision:IConvrtible
{
            Bool-agree;
            dateTime IConvertible.ToDateTime(IFormatProvider provider );
            {
                        Throw new InvalidCastException(" Cannot cast to DateTime");
            }
            //.other IConvertible Methods
}


ICloneable interface

When writing a program, you may need a copy of an object; for example, you may need to pass an object to another method and ensure that the changes made to the object by the method are not reflected in the current context. In such a case, you can use the ICloneable interface to create a new instance of an object of the same value as an existing instance. This is called cloning.

Cloning creates a new object and a new reference variable to that object. The ICloneable interface contains a new member method called Clone. This method creates a new object, that is a copy of the instance you wanted to clone. The resulting clone is of the same or a compatible type as the original instance.

Type of cloning

The .NET Framework CLS supports two type of cloning, shallow cloning and deep cloning. Shallow cloning involves copying an object without copying any references. Deep cloning involves making a copy of an object and any reference to other objects. You can implement the ICloneable interface in your class to enable deep cloning.

Up Next
    Ebook Download
    View all
    Learn
    View all