Ads block

Banner 728x90px

c#step13


C# Interface:

An interface in C# contains only the declaration of the methods, properties, and events, but not the implementation. It is left to the class that implements the interface by providing implementation for all the members of the interface. Interface makes it easy to maintain a program.
In C#, an interface can be defined using the interface keyword. For example, the following is a simple interface for a logging string message:
Interface Declaration:
interface ILog
{
    void Log(string msgToLog);
}
Now, different classes can implement ILog by providing an implementation of the Log() method, for example, the ConsoleLog class logs the string on the console whereas FileLog logs the string into a text file.
Implement interface using <Class Name> : <Interface Name > syntax.
Implement Interface
class ConsoleLog: ILog
{
    public void Log(string msgToPrint)
    {
        Console.WriteLine(msgToPrint);
    }
}

class FileLog :ILog
{
    public void Log(string msgToPrint)
    {
        File.AppendText(@"C:\Log.txt").Write(msgToPrint);
    }
}
Now, you can instantiate an object of either the ConsoleLog or FileLog class:
Instantiate Object
ILog log = new ConsoleLog();

//Or 

ILog log = new FileLog();

Explicit Implementation:

You can implement interface explicitly by prefixing interface name with method name, as below:
Impliment Interface Explicitly
class ConsoleLog: ILog
{
    public void ILog.Log(string msgToPrint) // explicit implementation
    {
        Console.WriteLine(msgToPrint);
    }
}
Explicit implementation is useful when class is implementing multiple interface thereby it is more readable and eliminates the confusion. It is also useful if interfaces have same method name coincidently.
Visit MSDN for more information on C# interface.
 Points to Remember :
  1. An interface only contains declarations of method, events & properties.
  2. An interface can be implement implicitly or explicitly.
  3. An interface cannot include private members. All the members are public by default.

No comments:

Post a Comment