Brett Lindsey
Brett Lindsey

Reputation: 29

What is this specific line of C# code relating to arrays is doing?

I'm doing some self paced learning and ran into this line of code that I'm not 100% certain I understand.

This is for a C# problem I'm working on. I know that the line is declaring the variable 'array' and saying that it is a new instance of this object. I'm confused about:

Code:

var array = new char[name.Length]

Upvotes: 0

Views: 161

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499840

Yes, the char part shows that the element type of the array is char. The equivalent code with an explicitly typed variable would be:

char[] array = new char[name.Length];

In terms of the Length property, that's just used to determine the size of the array. That's what the value within the [] always means when creating an array. For example, this creates an integer array with 5 elements:

int[] array = new int[5];

It may help to clarify things for your example if we separate things out:

int length = name.Length;
char[] array = new char[length];

Is that clearer to you?

The arrays section of the Microsoft C# Programming Guide can give more details about arrays in general.

Upvotes: 9

Related Questions