amit kohan
amit kohan

Reputation: 1618

instantiation and interface

I'm used to instantiate object as following:

type obj-name = new type();

and now I'm using

IList<string> str_element = new List<string>();

I was expecting to see something

IList<string> actors = new IList<string>();

can somebody give me some ideas why for interface instantiation is different here?

Thanks,
Amit

Upvotes: 1

Views: 140

Answers (4)

Daniel Becroft
Daniel Becroft

Reputation: 716

Interfaces define a contract, or set of functionality, that implementing classes must provide (at a minimum). By defining a variable of type IList<T>, you are really saying, "I don't care what the actual implementation is, it just needs to provide that functionality." This means you are divorcing the 'interface' and the 'implementation' in your calling code, which is a good thing.

The real power of interfaces is where you have pluggable code. If you were defining a library, rather than returning a List<T> instance, you could return an IList<T> instance (which AFAIK, is what the LINQ functionality does). This allows you to change the internal implementation of the object returned (it might be a linked list, or a B-Tree, or whatever), and calling code doesn't need to change.

Alot of the mocking libraries out there (e.g. NMock, Moq, etc) take advantage of interfaces and can generate implementing classes for testing purposes.

Upvotes: 1

MethodMan
MethodMan

Reputation: 18863

You can use LINQ: for example

This will give you something of a more Concrete Type.

using System.Linq;

IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList()

Upvotes: 0

Cole Tobin
Cole Tobin

Reputation: 9425

The reason you can't do = new IList<string>() is because IList<T> is an interface and you can't initialize interfaces as there is no body of code to call. I would reccomend doing

List<string> actors = new List<string>()

instead.

Upvotes: 3

SLaks
SLaks

Reputation: 888233

An interface is just that — an interface, or a specification of what methods should exist.
An interface does not contain any actual code.

Interfaces can only be used as types that hold concrete classes.
It doesn't make sense to create an instance of an interface, since there is nothing to instantiate.

Upvotes: 4

Related Questions