10

I found this code

Stream foo() 
{
  ...
  return new MemoryStream(new[] { a, b });
}

and can guess what it does, but cannot find an explanation why the type definition byte[] can be omitted. I looked at msdn c# new explanation, but that is too simple there.

datafiddler
  • 1,755
  • 3
  • 17
  • 30
  • 1
    It creates a `MemoryStream` instance which contains two bytes: `a` and `b` – Dmitry Bychenko Sep 14 '16 at 11:01
  • 4
    The type of the array can be derived from the arguments which are both bytes, so the array is a `Byte[]`. This is an [implicitly typed array](https://msdn.microsoft.com/en-us/library/bb384090.aspx) – Tim Schmelter Sep 14 '16 at 11:02
  • 2
    http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes – Yuval Itzchakov Sep 14 '16 at 11:04
  • You ought to have included the definition for `a` and `b`! – TaW Sep 14 '16 at 11:27
  • @TaW : yes, I ought to have ;). But I was unsure if the possible c'tors of `MemoryStream` or the actual type of a and b played the major role. – datafiddler Sep 14 '16 at 12:16

4 Answers4

9

You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer. The rules for any implicitly-typed variable also apply to implicitly-typed arrays.

Taken from https://msdn.microsoft.com/en-us/library/bb384090.aspx

ThePerplexedOne
  • 2,920
  • 15
  • 30
4

I can guess what it does

You are right, it is the same as new byte[] { a, b }

I cannot find an explanation why the type definition byte[] can be omitted

The reason it can be omitted is that both a and b are of type byte. The compiler is smart enough to figure out that you meant to create an array of bytes, so it does not ask you to specify the type explicitly.

Microsoft explains this shortcut here. The idea is similar to omitting the type in declarations that use var, when the actual type can be inferred from initialization context.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

The type definition can be omitted because it can be inferred from the type of the objects in the list.

The C# compiler does a lot of work analysing the code as it compiles to check that what you write is valid and will execute as you intend. You can still make mistakes, but (hopefully) fewer than in languages like c or C++.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
0

with that , basically you create an array of objects implicitly!

amdev
  • 6,703
  • 6
  • 42
  • 64