0

May I know the difference, if I can assign values to a array by

int [] marks = { 99,  98, 92, 97, 95};

Why do I see someone write this?

int [] marks = new int[]  { 99,  98, 92, 97, 95};

What is the difference?

Second question, since int is a primitive type, I can make an instance by

int i;

But I can see someone write like

int i = new int();

What is the difference again? Thanks a lot!

user196736
  • 71
  • 7
  • 2
    There is no difference the two ways of initializing an array. First approach is simpler in terms of writing a code. It offers you syntactical sugar but it does not initialize the array in different way. – Chetan Oct 11 '19 at 05:48
  • The int is just a keyword in the background it mean Int32 structure. Try it out! Click in the int keyword and press F12 – harmath Oct 11 '19 at 05:54
  • 1
    https://stackoverflow.com/questions/5678216/all-possible-array-initialization-syntaxes there are lotsa other ways, u know. – Hirasawa Yui Oct 11 '19 at 05:55
  • 1
    with `int i = new int();` you cannot initialize with a given integer value, but with `int i` you can do..`int i = 9` – Vivek Nuna Oct 11 '19 at 06:01
  • The shorter initializer syntax is more recent. Old-school is more verbose. – Ian Mercer Oct 11 '19 at 06:23

1 Answers1

0

General answer is that a) in C# you can achieve the same result in few ways and b) not all ways were available from the beginning.

For b) there are two parts:

  • code that has been written before new ways were added
  • new code written with old habbits - new ways are not always better than the old ones, they just look better :)

Re: array

Have a look at Array Initialization in Single-Dimensional Arrays (C# Programming Guide).

Object and Collection Initializers (C# Programming Guide) is also relevant.

Also, in Array Creation from new operator (C# reference) shows 3 ways (and that's not all the ways):

var a = new int[3] { 10, 20, 30 };
var b = new int[] { 10, 20, 30 };
var c = new[] { 10, 20, 30 };

There even is a Question here about all possible ways: All possible array initialization syntaxes.


Re: new int

There are two parts in the answer:

  1. With int i; (just a declaration) you cannot use before you initialise it.
  2. There are multiple ways to initialise variables, as with arrays.

Have a look at Initializing value types in Value types (C# Reference).

You can read there:

You can, of course, have the declaration and the initialisation in the same statement as in the following examples:

int myInt = new int();

–or–

 int myInt = 0;

For default values specifically, have a look at Default values table (C# reference). You can see there that you can also:

int a = default(int);

and from C# 7.1 even

int a = default;
Community
  • 1
  • 1
tymtam
  • 31,798
  • 8
  • 86
  • 126