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

    Should we initialize List(T) with size if known ?

    As per documentation, it says

    If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List.

    We can decrease the capacity of a List(T) any time by calling TrimExcess method over the List(T).
    If we decrease the capacity, interestingly, it is not decreased, but the memory is relocated and all the elements in the List(T) are copied into that memory location.

    dafault capacity if not defined is “0”. A List doubles itself, every time the capacity limit is hit.

    Capacity for the List could be checked easily, any time using List(T).Capacity property.

               List<string> animals = new List<string>();
                // get List<string> capacity
                int listCapacity = animals.Capacity;
                // get List<string> size
                int listSize = animals.Count;
                // reduce capacity 
                // make Lis<string> empty

    Using attributes in c#

    In the .NET Framework there are many reasons to use attributes, like

  • Defining which classes are serializable
  • Choosing which methods are exposed in a Web service
  • As per definition at MSDN
    Attributes allow us to add descriptions to classes, properties, and methods at design time that can then be examined at runtime via reflection.”

    Consider this example:
    Say you have a class which has a method from older version which is still in use for any reason and now you have come up with a new version of the class which makes fantastic use of Generic List and LINQ and has a new method for similar purpose. You would like developers to prefer the new one provided in the later version of your library. How will you do that ? One way is to write in the documentation. A better way is to use attribute as follow.

    public class AccountsManager
          [Obsolete("prefer GetAccountsList", true)]
          static Account[] GetAccounts( ) { }    
          static List<Account> GetAccountsList( ) { }      

    If an obsolete method is used when the program is compiled, the developer gets this info and decides accordingly.

    AccountManager.GetAccounts() is obsolete: prefer GetAccountsList

    We may also create and add Custom Attributes as per requirements.

    References :

  • Use the advantages of custom attributes in your C# applications
  • Using Attributes in C#
  • Dev Quotes #01

    PM says, it’s ready, it’s not. QA says, it’s ready,
    it’s not., you say, it’s ready, it’s not .  When is it ready then!
    When the product says this  itself.

    by “anonymous dev”

    Dance like all watching.
    Sing like all listening.
    Code like all peer reviewing

    by “anonymous dev”

    All developers get it done right.
    Many developers get it done right, for the first and for all.
    Some developers get it done right, for the first and for all and set examples.
    Countable developers get it done right, for the first and for all, set examples and then not only change the way we program but how people live.

    by “anonymous dev”

    Tweet Me

    DefaultModelBinder class in System.Web.Mvc

    While working with validation for an  MVC application I came across option for using  DefaultModelBinder class.

    public class DefaultModelBinder : IModelBinder

    maps following types in response to a request.
    primitive types, model classes and collections

    What it does is, it takes the required object from the model, binds its properties to the corresponding HTML fields of the form (View).

    If the class it is binding implements IDataErrorInfo interface, which binds the developer to implement following properties

    Error:  string Error { get; }
    Item :  string this[string columnName] { get; }

    If a class implements the interface, it ftches the value for the fields, by invoking IDataErrorInfo.this indexer.

    What you can do interesting is you can perform your validation / checks and over an object in focus and  if in case it fails to correspond with the requirements, like a customer has provided wrong value for the name of something, It will return the error value , custom provided  at the time of implementation of the interface. Have a look.

    Here are details for DefaultModelBinder