generic list constructor

  • Thread starter Thread starter Andy Fish
  • Start date Start date
A

Andy Fish

Can Someone explain why this snippet doesn't work in C# 2.0:

Foo foo = new Foo();
List<Foo> lf = new List<foo>( { foo } );

whereas this works:

Foo foo = new Foo();
Foo[] af = { foo };
List<Foo> lf = new List<foo>( af );

It seems to me that the expression { foo } returns an array of Foo with only
one element in it, which should therefore be acceptable as IEnumerable<Foo>
to be passed into the generic list constructor.

TIA

Andy
 
Can Someone explain why this snippet doesn't work in C# 2.0:

Foo foo = new Foo();
List<Foo> lf = new List<foo>( { foo } );

whereas this works:

Foo foo = new Foo();
Foo[] af = { foo };
List<Foo> lf = new List<foo>( af );

It seems to me that the expression { foo } returns an array of Foo with only
one element in it, which should therefore be acceptable as IEnumerable<Foo>
to be passed into the generic list constructor.

TIA

Andy

Try:
List<Foo> lf = new List<foo>(new Foo[] { foo } );

In 3.5 the initialization of classes, collections were improved a lot,
these improvements do not exist in 2.0 though.
 
message
Can Someone explain why this snippet doesn't work in C# 2.0:

Foo foo = new Foo();
List<Foo> lf = new List<foo>( { foo } );

whereas this works:

Foo foo = new Foo();
Foo[] af = { foo };
List<Foo> lf = new List<foo>( af );

It seems to me that the expression { foo } returns an array of Foo with
only
one element in it, which should therefore be acceptable as
IEnumerable<Foo>
to be passed into the generic list constructor.

TIA

Andy

Try:
List<Foo> lf = new List<foo>(new Foo[] { foo } );

In 3.5 the initialization of classes, collections were improved a lot,
these improvements do not exist in 2.0 though.

hmm thanks, that works too - although i still don't really understand
exactly why my original example was invalid
 
Back
Top