2

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.

Scott Adams
  • 410
  • 3
  • 11
oldDavid
  • 176
  • 1
  • 8
  • [This](http://stackoverflow.com/questions/291413/how-to-declare-an-array-inline-in-vb-net) might help, particularly Jon Skeet's answer is a little different then what you have here. – Cemafor Apr 30 '13 at 17:23
  • I the problem the array formulation or creating the new `Product`s? – Cemafor Apr 30 '13 at 17:27

1 Answers1

9

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.

Ric
  • 12,855
  • 3
  • 30
  • 36