Simple Interface Example in C#

The following shows a simple example of how Interfaces can be very useful in C#.  Here SomeOtherClass doesn’t care what’s passed in as long as it conforms to ILog, then it will be able to call the Log function – this is truly polymorphic guys!

 

public interface ILog
{
 void Log(string text);
}
public class FileLog : ILog
{
 public void Log(string text)
 {
  // write text to a file
 }
}
public class DatabaseLog : ILog
{
 public void Log(string text)
 {
  // write text to the database
 }
}
public class SomeOtherClass
{
 private ILog _logger;
 public SomeOtherClass(ILog logger)
 {
  // I don't know if logger is the FileLog or DatabaseLog
  // but I don't need to know either as long as its implementing ILog
  this._logger = logger;
  logger.Log("Hello World!");
  }
}
Advertisements
Simple Interface Example in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s