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- : <interface name >
syntax.
Interface implementation Example:
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:
C#:
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:
C#:
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.
Points to Remember :
- An Interface only contains declarations of method, events & properties.
- An Interface can be implement implicitly or explicitly.
- An Interface cannot include private members. All the members are public by default.
Visit MSDN for more information on interface.