Help with generic list

  • Thread starter Thread starter kurt sune
  • Start date Start date
K

kurt sune

I need help with translating this:

This works i C#
List<Customer> customers = new List<Customer> {

new Customer { Fullname = "Pelle" },

new Customer { Fullname = "Oskar" },

new Customer { Fullname = "Hasse" },

new Customer { Fullname = "Zrjan" },

new Customer { Fullname = "Harald" },

new Customer { Fullname = "Adam" }};


This does not work in VB:

Dim customers As New List(Of Customer) _

(New Customer With {.Fullname = "Pelle"}, _

New Customer With {.Fullname = "Oskar"}, _

New Customer With {.Fullname = "Hasse"}, _

New Customer With {.Fullname = "Zrjan"}, _

New Customer With {.Fullname = "Harald"}, _

New Customer With {.Fullname = "Adam"})



Can someone please tell me why?


/k
 
kurt sune said:
I need help with translating this:

This works i C#
List<Customer> customers = new List<Customer> {

new Customer { Fullname = "Pelle" },

new Customer { Fullname = "Oskar" },

new Customer { Fullname = "Hasse" },

new Customer { Fullname = "Zrjan" },

new Customer { Fullname = "Harald" },

new Customer { Fullname = "Adam" }};


This does not work in VB:

Dim customers As New List(Of Customer) _

(New Customer With {.Fullname = "Pelle"}, _

New Customer With {.Fullname = "Oskar"}, _

New Customer With {.Fullname = "Hasse"}, _

New Customer With {.Fullname = "Zrjan"}, _

New Customer With {.Fullname = "Harald"}, _

New Customer With {.Fullname = "Adam"})



Can someone please tell me why?


Dim Customers As New List(Of Customer)( _
New Customer() { _
New Customer With {.Fullname = "Pelle"}, _
New Customer With {.Fullname = "Oskar"} _
} _
)

In C#, the {...} is called a "Collection Initializer" (see 7.5.10.3 C#
language spec) which does not exist (AFAIK) in VB.Net in exact the same way.
So you must help yourself by creating an array. However, the 1:1 VB
translation would not make use of an array but...:

dim tmp1, tmp2 as customer
tmp1 = new Customer With {.Fullname = "Pelle"}
customers.add(tmp1)
tmp2 = new Customer With {.Fullname = "Oskar"}
customers.add(tmp2)

That's what the IL code of the C# version produces.

See also:
http://www.eggheadcafe.com/software/aspnet/33184658/collection-initializer-in.aspx


Armin
 
Back
Top