Why use interfaces

This a general overview about what are the advantages for using interfaces in C#. Here are some the many reason fro which we should consider using an interface while development.

  • To make use of multiple inheritance
  • C# does not allow multiple class inheritance. We can derive from only one class at a time, but not more. We can indeed inherit our class, interface from multiple interfaces.

    public class ClassB : ClassA, InterFaceA, InterFaceB
    {
     //
    }
    
  • If we expect similar behaviour from many classes, it is better to inherit them from an Interface. This makes it easy for plug-in style development and future extension of components.
  • Interfaces provide flexibility and support for Unit Testing. Most of the Testing Frameworks rely on Interfaces for Mock objects , which are created and provided with the dependencies inside the Test code Block. Instead of creation from classes, these Mocking frameworks need an Interface.
  • Interface allow us maximum flexibility for the adoption of change, without the much headache and breaking builds.
  • Interfaces are more flexible than base classes. We can define a single implementation that can implement multiple interfaces.
  • Inversion of control and dependency Injection totally rely over interfaces.
  • A very important building unit, Struct, cannot inherrit from classes but can inherit from an Interface.
  • Consider this example:
    You have a class that is capable of playing media files(mp3). You give that class to you friend who tries to play MPEG type of files. It would not be possible for him to do so without making significant changes to you class.

    public class MusicPlayer 
    {
       void Play(Mp3 _mp3File){}
    }
    

    Now consider this
    Instead of passing type of mp3 file to Play Method what if you pass this Method, a derived from an interface of Type MediaType.

    public interface MediaType
    { }
    
    public class Mp3 : MediaType
    { }
    
    public class MPEG : MediaType
    { }
    
    public class MusicPlayer 
    {
       void Play(MediaType _mediaFile){}
    }
    

    In this scenario, you can derive another MediaFile type and from MediaType like MPEG and pass that to the Play Method and it will happily accept it and play it for you (provided logic).

    public class TestPlayers
        {
            public void PlayMedia()
            {
                MusicPlayer musicPlayer = new MusicPlayer();
                musicPlayer.Play(new Mp3());
                musicPlayer.Play(new MPEG());
            }       
        }
    

    for reference and more information:

  • Significance of Interfaces C#
  • Advertisements

    Working with Files in c# – intoduction

    Here are some of many classes available to work with files

    using TextReder and TextWriter classes

    string filePath = @"E:\TestDocument.txt";
    
    // open file to read
    TextReader tr = File.OpenText(filePath);
    Console.WriteLine(tr.ReadToEnd());
    
    // must close file after reading
    tr.Close();
    
    string filePath = @"E:\TestDocument.txt";
    
    // open file to read
    TextReader tr = File.OpenText(filePath);
    Console.WriteLine(tr.ReadToEnd());
    
    // must close file after reading
    tr.Close();
    

    using StreamReader and and StreamWriter classes

    // open file to read file 
    StreamReader sr = new StreamReader(filePath); 
    Console.WriteLine(sr.ReadToEnd());
    
    // must close file after writing
    sr.Close();
    
    // open file to write
    StreamWriter sw = new StreamWriter(filePath);
    sw.AutoFlush = true;
    Console.WriteLine(sw.Encoding);
    Console.WriteLine(sw.FormatProvider);
    sw.WriteLine("Hello World");
    
    // must close file after writing
    sw.close()
    

    Reading / writing To IsolatedStorageFile using IsolatedStorageFileStream

    // declare file IsolatedStorageFile
    IsolatedStorageFile isoStore = 
    IsolatedStorageFile.GetUserStoreForAssembly();
    
    // create file Stream
    IsolatedStorageFileStream isoFS =
                    new IsolatedStorageFileStream("temp.txt", FileMode.Create, FileAccess.Write);
    
    // write to file
    sw = new StreamWriter(isoFS);
    sw.WriteLine("in iso storage" + "\n");           
    sw.WriteLine("in iso storage FInished");
    
    // must remember to close or the resouce is kept locked
    sw.Close();
    
    // read from IsolatedStorageFile
    isoFS = new IsolatedStorageFileStream("temp.txt", FileMode.Open, FileAccess.Read);
    sr = new StreamReader(isoFS);
    Console.WriteLine(sr.ReadToEnd());
    

    Working with StringBuilder in C#

    This Post will look in to several Methods provided with StringBuilder class. There are several ways to declare and initialize an instance of StringBuilder class.

    // declare StringBuilder instance
    StringBuilder sb;
    
    // default constructor
    sb = new StringBuilder();
    
    // new stringbuilder with initial capacity 
    sb = new StringBuilder(10);
    
    // new stringbuilder with with a new string
    sb = new StringBuilder("codingphobia.com");
    
    // initial with initial capacity
    // and max limit over capacity
    sb = new StringBuilder(10, 100);
    
    // new stringbuilder with with a new string
    // and max limit over capacity
    sb = new StringBuilder("codingphobia.com", 1000);
    
    // new stringbuilder with new string
    // start index to place string
    // length of string
    //  max limit over capacity
    sb = new StringBuilder("codingphobia.com", 10, 16, 1000);
    

    Here are some of the built-in methods

    // append string to stringbuilder
    Console.WriteLine(sb.Append("First"));
    
    // get current capacity
    Console.WriteLine("current string capacity: " + sb.Capacity);
    
    // compare string with stringbuilder
    Console.WriteLine(sb.Equals("First"));
    
    // get the hash code for the string builder
    Console.WriteLine(sb.GetHashCode());
    
    // get the type for the object
    Console.WriteLine(sb.GetType());
    
    // get the length for the string
    Console.WriteLine(sb.Length);
    
    // gt the capacity for stringbuilder
    Console.WriteLine(sb.Capacity);
    
    // gt the max capacity for stringbuilder
    Console.WriteLine(sb.MaxCapacity);
    
    // get the string anfd write to console
    Console.WriteLine(sb);
    
    // insert char at specific index
    Console.WriteLine(sb.Insert(2, '-'));
    
    // replace a char at specific index
    Console.WriteLine(sb.Replace('-', ' '));
    
    // remove a char from specific index
    Console.WriteLine(sb.Remove(2, 1));
    

    Following methods allows us to extend our stringbuilder with appending value at the end.

    // Add string at the end of stringbuilder
    sb.Append("new string");
    
    // Add string with end of line at the end of stringbuilder
    sb.AppendLine("new string");
    
    // Add string at the end of stringbuilder, 
    // with information about the format etc
    sb.AppendFormat(new CultureInfo("en-US"),
                    "# # # ### ##", new char[] { 'A', 'S', 'D', 'F' });
    

    Following methods show how can we extend our string builder using insert method which has 18 overloads.
    most common are as follows

     // insert char at 0 index 
     sb.Insert(0, '0');
    
     // insert bool at 0 index
     sb.Insert(0, true);
    
     // insert char Array at 0 index
    sb.Insert(0, new char[] { '0', '1' });
    
    // insert double value at 0 index
    sb.Insert(0, 10.00);
    
    // insert decimal value at 0 index
    sb.Insert(0, 10);
    
    // insert char Array value, from  index 2 to 3,
    // at index 0 of string builder
    sb.Insert(0, new char[] { '1', '2', '3', '4' }, 1, 1);
    
    // insert string at 0 index
    sb.Insert(0, "a String");
    

    Implicit versus Explicit implementation of Interfaces in C#

    What is the differences in implementing an interfaces implicitly or explicitly in C#?

    Suppose we have an interface IWriter as follows

        public interface IWriter
        {
            public void WrtiteTo()
            { }
        }
    

    Implicit: When we implement an interface implicitly, the implementing class exposes new behaviours. It is simply adding the methods, properties or other items required by the interface directly to the class and as public methods. So winding up, A member does this work for you in class which is implementing certain interface. Here is the sample which implements IWriter Interface implicitly:

        public class DocumentWriter : IWriter
        {
            #region IWriter Members
            public void WrtiteTo()
            {
                // Some Logic here
            }
            #endregion
        }
    

    Implicit: On the other hand Explicit implementation are exposed by the use of interface itself itself. Here is the sample which implements IWriter Interface Explicitly:

        public class DocumentWriter : IWriter
        {
            #region IWriter Members
            void IWriter.WrtiteTo()
            {
                 // Some Logic here
            }
            #endregion
        }