6

I'm trying out a program which I found on the net. Why is it necessary to put to curly braces at the end of the statement? It gives an error: "Byte has no constructors".

Dim data As Byte() = New Byte(1023) {}

I can't put the code like this either, it produces the error "byte cannot be a 1-dimensional array".

Dim arr As Byte() = New Byte()

Can you explain to me why this is happening?

2 Answers 2

14

Some flavors

    Dim b() As Byte 'b is nothing
    Dim b1(1023) As Byte 'b1 is an array of 1024 elements, all equal to 0
    Dim b2() As Byte = New Byte() {85, 99, 1, 255} 'four elements

    b = New Byte() {} 'zero element array
    b = New Byte() {1, 2} 'two element array

Inference is generally a bad idea.

1
  • 1
    accepted answer answers OP's question "Can you explain to me why this is happening?" This answer shows examples how to do it right. This is what I needed thanks. Feb 28, 2018 at 19:11
7

You need curly braces, because if you don't put them, it means you're trying to call a constructor for a single object -- which is an error for different reasons:

  1. You can't assign a single object to an array. (This is always true.)
  2. Byte doesn't have a constructor. (This is only true in this particular case.)
20
  • When you said As Byte() instead of As Byte.
    – user541686
    Feb 19, 2011 at 3:10
  • LOL, I didn't even knew that represented an array initialization. I have a long way to go :P Feb 19, 2011 at 3:12
  • @abcdefghijklmnopqrstuvwxyz: Haha okay... if you're using Visual Basic 2008 or later, then you can use type inference and omit the As Byte() part entirely -- that way, the variable will have the same type as whatever you assign it.
    – user541686
    Feb 19, 2011 at 3:14
  • @Mehrdad: Type Inference stuff sounds easy. Thanks mate :) + 1 Feb 19, 2011 at 3:22
  • Ugh, I just removed my up-vote because you recommended type inference in VB.NET. That's a very bad idea. It doesn't work exactly the same way as var in C#. Just learn how to declare variables and what the appropriate syntax is. It's not that hard. If you don't know the difference between an array and an object, you're going to have a lot of problems anyway. No reason to create additional ones by programming with Option Infer On. Feb 19, 2011 at 7:11

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.