简体   繁体   中英

A C# syntax question

I am currently teaching myself c# but am confused by the following syntax:

new Deck( new Card[] {} )

where the Deck constructor looks like this:

public Deck(IEnumerable<Card> initialCards)

what does the {} bit mean?

It is an array initializer , and in this instance initializes an empty array.

It can also be used as follows:

int[] bling = new [] { 1, 2, 3 };

or

int[] bling = { 1, 2, 3 };

It is a collection initializer, can be used as follows

new Card[] {
    new Card(),
    new Card(),
    new Card()
};

To initilise an array of cards of length 3 containing three card objects. As you have it, it will be an empty array.

It initialize an empty array.If you have a class like this :

class student {
    private string name;
    private int age;
}

you can initialize this :

student a = new student { name = "a", age = 10};

Sorry for my mistake above. You can initilize an array of student :

student[] students = new student[] {new student {name = "a", age = 10}, new student {name = "b", age = 20 }};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM