oldDavid
oldDavid

Reputation: 176

How to do array creation in vb.net using object initializers to set properties

I'm looking at the code sample on http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

As an exercise, I'm trying to translate it from C# into vb.net but having no luck with this piece,

    public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
    }
     Product[] products = new Product[] 
       { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
         new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
         new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
            };

I tried

      Public class Product
         Public Property Id As Integer
         Public Property Name As String
         Public Property Category As String
         Public Property price As Decimal
      End Class

    Dim products() As Product = { _
         new Product (Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 ), _
         new Product ( Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M ), _
         new Product (Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M ) }

I've seen recommendations to use a List instead of an array so I'm going to try that but would like to know what I'm missing here.

Upvotes: 2

Views: 1312

Answers (1)

Ric
Ric

Reputation: 13248

Take a look at object initializers:

Dim namedCust = New Customer With {.Name = "Terry Adams".....

notice the With aswell as the '.' for each of the properties you want to set.

 Dim products() As Product = { _
         new Product With {.Id = 1, .Name = "Tomato Soup", .Category = "Groceries", 
                           .Price = 1 }, _.....

MSDN Link

Further reading.

Upvotes: 9

Related Questions