none
Instantiate a class and assign it to an interface variable RRS feed

  • Question

  • http://stackoverflow.com/questions/1176416/implementing-ilist-interface

    I as looking at the implementation of the IList interface using the above linke. The private member of the class has been declared as

            private readonly IList<T> _list = new List<T>();
    I don't quite understand how we can instantiate a class List<T> and assign it to an interface variable _list. My understanding was that an interface was a contract of methods that need to be implemented when a class derives from it. What exactly is happening here? It compiles without problems.

     




    Saturday, March 28, 2015 3:54 PM

Answers

  • You  can't  create interface or abstract class  instance , but you can  have variable of type Interface and can save in that variable any Class' object  which inherit from interface

    Saturday, March 28, 2015 4:04 PM

All replies

  • You  can't  create interface or abstract class  instance , but you can  have variable of type Interface and can save in that variable any Class' object  which inherit from interface

    Saturday, March 28, 2015 4:04 PM
  • thanks, it looks like an internal implementation / work-around to instantiate an interface. Since you cannot instantiate an interface, you instantiate a class that inherits from the interface and then assign it to a variable which in turn allows to access the members of the interface (methods and properties).

    Saturday, March 28, 2015 4:31 PM
  • "thanks, it looks like an internal implementation / work-around to instantiate an interface"

    Well, it's certainly not a workaround, it's perfectly normal thing to do. It's perhaps not very common but people sometimes do this because it makes code changes easier - you can swap List<T> for another IList<T> implementation without changing the rest of the code. At least that's how the theory goes, in practice you can change List<T> for T[] and then the code that uses IList<T>.Add will start throwing exceptions at runtime.

    "variable which in turn allows to access the members of the interface (methods and properties)."

    With the exception of explicit interface implementation you can access the members of the interface anyway. For example, there's no difference between IList<T>.Add and List<T>.Add.

    Sunday, March 29, 2015 7:46 AM
    Moderator