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!

1 Answer 1

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}
        }
Sign up to request clarification or add additional context in comments.

4 Comments

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,...}.
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.
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".
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.