generics

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hi!

In a book they use number _1 below but will it be the same if I instead use
number_2 below
I think so because List<T> implements IEnumerable<T>
So according to my knowlwdge it would be the same.
I'm I right in my conclusion ?

1. public Vectors(IEnumerable<Vectors> initialItems)
{...}
2. public Vectors(List<Vectors> initialItems)
{...}


//Tony
 
Hi Tony!

Tony Johansson said:
So according to my knowlwdge it would be the same.
1. public Vectors(IEnumerable<Vectors> initialItems)
{...}
2. public Vectors(List<Vectors> initialItems)
{...}

No, you are wrong. These functions are not the same.

1st can take any IEnumerable that contains Vectors.
2nd can only take a generic List that contains Vectors.

1st is more open to implementors that want to use this function but they
can only use the methods that are defined by IEnumerable. (so 2nd is
limited but you can use all methods of List in there)

Konrad
 
Hi!

In a book they use number _1 below but will it be the same if I instead use
number_2 below
I think so because List<T> implements IEnumerable<T>
So according to my knowlwdge it would be the same.
I'm I right in my conclusion ?

1. public Vectors(IEnumerable<Vectors> initialItems)
{...}
2. public Vectors(List<Vectors> initialItems)
{...}


//Tony

Version 1 could take a Queue<Vectors>, while version two could not, as
an example. Version 1 is a superset of version 2.
 
In a book they use number _1 below but will it be the same if I instead use
number_2 below
I think so because List<T> implements IEnumerable<T>
So according to my knowlwdge it would be the same.
I'm I right in my conclusion ?

1. public Vectors(IEnumerable<Vectors> initialItems)
{...}
2. public Vectors(List<Vectors> initialItems)
{...}

#1 can be called with List<Vectors>, Vectors[] and lots of other
types.

#2 can only be called with List<Vectors>.

So #1 can be used in more contexts than #2.

But there is a downside as well.

In #1 you can only use the methods in IEnumerable<>.

In #2 you can use all methods of List<> which is a
super set of the methods in IEnumerable<>.

So #2 gives more possibilities inside the method.

Your choice.

Note that you can chose to have both version !

Arne
 
Back
Top