Three Popular C# Interfaces

C# is a typical object-orient programming language. It offers all the support you need to create your own class hierarchies and to use them in the most efficient way.

Interfaces are the key concept inside C#. An interface contains a public signature of Methods, Properties, Event, and Indexes. A class or a structure can implement an interface.

In this article, I will show most of the popular built-in interfaces that you can use to enhance your class hierarchies.

IComparable interface

Contains one method that you can use to sort the elements.

int CompareTo(object obj);

The CompareTo method returns an int value that shows how two elements are related to each other. The possible values are -

  • < 0 which means the current instances precedes the specified object in the sort order.
  • = 0 whch means that the current instance is in the same position of a specified object in the sort order.
  • > 0 which means that the current instance follows the specified object in the sort order.
Ex
  1. // Implementing IComparable interface to make the object sortable   
  2.     class Car : IComparable  
  3.     {  
  4.         public string Name { getset; }  
  5.         public int TopSpeed { getset; }  
  6.   
  7.         // The implementation method  
  8.         public int CompareTo(object obj)  
  9.         {  
  10.             // Convert the spciefied object to a car   
  11.             Car car = (Car)obj;  
  12.   
  13.             // Compare between the current instance and the specified object   
  14.             if (this.TopSpeed > car.TopSpeed)  
  15.                 return 1;  
  16.             else if (this.TopSpeed == car.TopSpeed)  
  17.                 return 0;  
  18.             else  
  19.                 return -1;  
  20.                   
  21.         }  
The code for using this method.
  1. static void Main(string[] args)  
  2.        {  
  3.            // Using of this objects   
  4.            List<Car> cars = new List<Car>();  
  5.            cars.Add(new Car  
  6.            {  
  7.                TopSpeed = 200  
  8.            });  
  9.            cars.Add(new Car  
  10.            {  
  11.                TopSpeed = 180  
  12.            });  
  13.   
  14.            cars.Sort(); // This method will call the CompareTo method in each object to sort the objectes   
  15.        }  
IDisposable interface

This interface is very powerful if your class works with unmanaged resources (files, streams, database connections .etc.). This interface contains one method.

void Dispose();

When you implement this method, you can free any unmanaged and external resources that you’ve used in your class instance.

ex
  1. // Implementing IDisposable Interface to free the unmanaged resources that your instance will work with   
  2.   class FileManager : IDisposable  
  3.   {  
  4.       FileStream fs;  
  5.   
  6.       public FileManager(string filePath)  
  7.       {  
  8.           fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);   
  9.       }  
  10.   
  11.       // Method to write  
  12.       public void Write(byte[] data)  
  13.       {  
  14.           fs.Write(data,0,data.Length);   
  15.       }  
  16.   
  17.       // The implemntation method to free any unmanaged resources   
  18.       public void Dispose()  
  19.       {  
  20.           fs.Close();  
  21.       }  
  22.   
  23.   }  
The code for using this method.
  1. static void Main(string[] args)  
  2.         {  
  3.             // Using statment will call the Dispose Method after the statment is finished  
  4.             using (FileManager manager = new FileManager("welcome.data"))  
  5.             {  
  6.                 byte[] data = Encoding.ASCII.GetBytes("Hello C#");   
  7.                 manager.Write(data);   
  8.             }   
  9.         } 
IFormattable interface

The IFormattable interface converts any object to its representation string depending on the specific format provider and it contains only one method.

string ToString(string format,IFormatProvider provider);

Ex
  1. // The implemntation of the IFormattable interface to convert any object to its represntation string  
  2.    class Person : IFormattable  
  3.    {  
  4.        public string FirstName { getset; }  
  5.        public string LastName { getset; }  
  6.   
  7.        // This method to convert the object to string depends on a specific format and culture   
  8.        public string ToString(string format, IFormatProvider formatProvider)  
  9.        {  
  10.            if (formatProvider == null)  
  11.                formatProvider = System.Globalization.CultureInfo.CurrentCulture;  
  12.   
  13.            switch (format)  
  14.            {  
  15.                case "FL":  
  16.                    return FirstName + " " + LastName;  
  17.                case "LF":  
  18.                    return LastName + " " + FirstName;  
  19.                case "F":  
  20.                    return FirstName;  
  21.                case "L":  
  22.                    return LastName;   
  23.                default:  
  24.                    throw new ArgumentException("This format is not provided");   
  25.            }  
  26.        }  
  27.    }  
The code for using this method.
  1. static void Main(string[] args)  
  2.         {  
  3.             Person person = new Person  
  4.             {  
  5.                 FirstName = "Ahmad",  
  6.                 LastName = "Mozaffar"  
  7.             };  
  8.   
  9.             Console.WriteLine(person.ToString("FL"null)); // Ahmad Mozaffar  
  10.             Console.WriteLine(person.ToString("LF"null)); // Mozaffar Ahmad  
  11.             Console.WriteLine(person.ToString("F"null));  // Ahmad  
  12.             Console.WriteLine(person.ToString("L"null));  // Mozaffar  
  13.         }  
Conclusion

Thses interfaces are the most common interfaces that you can use to create robust objects. There are also many interfaces such as -IEnumberable, IQuerable, IList<>, but the above three are very important.