0

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:

  • Is this stating that the array will contain characters as its' data type?
  • How the .Length operator being used here? Is this saying that the data that each cell is storing is number of characters, and not the characters themselves, in each cell of the array?

Code:

var array = new char[name.Length]

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.