4

I'm trying to create a typed-sized parameters array in VB.Net:

Dim parameters() As SqlParameter = New SqlParameter() _
        {
          New SqlParameter("@first_name", SqlDbType.VarChar, 50) {Value = "john"},
          New SqlParameter("@last_name", SqlDbType.VarChar, 50) {Value = "doe"},
          New SqlParameter("@age", SqlDbType.Int) {Value = 18},
          New SqlParameter("@id", SqlDbType.Int) {Value = 123}
        }

But VS says: Value' is not declared. It may be inaccessible due to its protection level

What's wrong with the code above?

Thanks!

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Fabio Belz
  • 258
  • 2
  • 6
  • 12

1 Answers1

11

You need to use the VB syntax for object initializers:

Dim parameters() As SqlParameter = New SqlParameter() _
        {
          New SqlParameter("@first_name", SqlDbType.VarChar, 50) With { .Value = "john"},
          New SqlParameter("@last_name", SqlDbType.VarChar, 50) With { .Value = "doe"},
          New SqlParameter("@age", SqlDbType.Int) With { .Value = 18},
          New SqlParameter("@id", SqlDbType.Int) With { .Value = 123}
        }
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • 1
    The syntax is a mess in VB.NET, that's the reason why i would never initialize an array this way. Instead i would create the parameters one after another, set the values and then add them to an array(eg. `{param1,param,...}`. – Tim Schmelter Apr 17 '13 at 22:07
  • 2
    Why is it a mess? It's just different from c#. Don't get me wrong, I prefer c# too, but don't see what's wrong with this. – Kenneth Apr 17 '13 at 22:08
  • Because it is not readable. Is it an array, is it an object, is there a nested array or ist an intialization or just a property, do i need an `_` to concat two lines or not, where are the braces allowed, do i need `With` or `From`, do i have to use a point or comma or not? It's much more readable to not use this "one-liner". – Tim Schmelter Apr 17 '13 at 22:11
  • 1
    I guess that's just a matter of getting used to it. I used VB for a while and to be honest, I got used to it quite quickly. Anyway, each his opinion, let's not hijack this thread to make a point about VB <=> c#. Cheers! – Kenneth Apr 17 '13 at 22:12