How to role usage of c# IList interface type or other interface as type?

StackOverflow https://stackoverflow.com/questions/23685891

  •  23-07-2023
  •  | 
  •  

سؤال

IList is a interface. I have just started learning generics. And I know interface is a contract that class implements it promises to use its methods. So I never thought about it using like value type like:

Can someone please explain me what does this and how to think of its usage when using an interface like type:

IList<Writer> someName;

I am creating here generic typ of IList interface. But interface is not a class so how should I imagine it role?

Or am I misunderstanding something?

هل كانت مفيدة؟

المحلول

If a member/variable is declared as an interface, it can be instantiated with any class that implements said contract. For example, you could instantiate someName with List<Writer>(), but not with new IList<Writer>().

IList<Writer> someName = new List<Writer>();
// someName can access any member of IList, but not specific members of List

نصائح أخرى

IList<Writer> someName;

Will hold a reference to any class instance that implements the IList<T> Interface, with Writer specified as the type parameter.

 // Returning from list
        List<Writer> myWriters = new List<Writer>();
        myWriters.Add(new Writer("Andy", "FL"));
        myWriters.Add(new Writer("Mary", "FL"));
        myWriters.Add(new Writer("Ken", "CA"));
        myWriters.Add(new Writer("Robert", "WA"));
        myWriters.Add(new Writer("Brian", "CA"));

        IList<Writer> roWriters;
        roWriters = myWriters.AsReadOnly();

So can I say this; above using IList allow myWriters to use .AsReadOnly(); method? Otherwise it would not be possible? .AsReadOnly(); is a method of IList no List itself?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top