简体   繁体   中英

What do square brackets mean in this context in C#?

What do the square brackets mean in a new expression in C# as follows:

public class MyClass
{
    public string Name { get; set; }
}

// ...

    var x = new MyClass[0]; // <-- what is this?

This is an array declaration The use of var just allows the compiler to decide on the type

MyClass[] classArray = new MyClass[0];

The 0 inside the [] indicates that the number of array 'spaces' is 0

var classArray = new MyClass[5];

This will create an array of length 5, and the use of var will allow the compiler to decide on the type, which will be MyClass[]

You can access each place in the array I created above by using indexers, mentioned in another answer, similar to this, let's say MyClass has a property called name with public get and set accessors(stupid example I know)

classArray[1] = new MyClass();
classArray[1].Name = "Daniel's class";

This allows us to access the MyClass object held in the second array placement, this is indexing

We can also create an array like this, let's say that the MyClass has a constructor that takes a string for the Name property

var x = new [] {
  new MyClass("Daniels"), 
  new MyClass("Yours"), 
  new MyClass("Ours")
};

Forgive me for my bad examples

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