0

I already know that byte[] b = new byte[8]; works fine. But why doesn't byte[] b = new byte[8]; work?

For example, byte b = new byte(); works fine, so an array style also should work but it doesn't. I have no exact idea of this reason. Could someone please explain?

shapiro yaacov
  • 2,308
  • 2
  • 26
  • 39
myoldgrandpa
  • 871
  • 7
  • 21

1 Answers1

2

An Array does not have a constructor, when you create an array you are creating a list or collection of objects, it is the objects that make up the array that will have the constructor, for example.

var b = new byte[8];

will create an array of 8 objects of type byte where each element of the array will be null, using constructor notation is invalid but you can use the initializer notation, eg.

var b = new byte[8] { new byte(), new byte(), ... };

Using this notation will initialize the array of 8 elements of type byte to a new instance of byte

In short var b = new byte() is a instantiating a variable as a byte and calling the constructor of the object, var b = new byte[8] is creating an array of n elements of type byte each initialized to null.

I hope that helps

Neil Stevens
  • 3,534
  • 6
  • 42
  • 71
  • var b = new byte[8]; does not create an array with null elements. Since byte is a value type, each element will be initialized with 0. If the array were a string or another reference type, then the slots would be initialized with null. – esteuart Jan 20 '17 at 18:23