Search code examples
c#listgenericsinterfaceilist

How an interface can replace a class?


I created a Method called GetStudentMarks(). The return-type of this method is generic List<StudentMark>.The code works well even when i replaced the List<StudentMark> with generic IList<StudentMark>. How can an interface replace a class while interface contain only the declarations?


Solution

  • An interface cannot replace a class. It's just a blueprint for a class that has some implementation that corresponds by the guidelines that are set by the interface. So, you mostly will have one interface and than 1 or multiple classes that have some implementation for that interface like so:

    public interface IMyInterface{
     IList<string> SomeList { get; }
    }
    
    public class MyClass : IMyInterface {
      public IList<string> SomeList {
        get { 
          return new List<string>(){ "a", "b" , "c" }; 
        }
      }
    }