String Array in C#

I am totally missing the point here. How do I make something simple as a string array (or something like it?) in C#?

Whoever shows me the easy code first receives a cookie!

int[ ] numbers = new int[ ] {1, 2, 3, 4, 5};
int[ ] numbers = new int[5];
string[ ] names = new string[ ] {"Matt", "Joanne", "Robert"};

You can also omit the new operator if an initializer is provided, like this:

int[ ] numbers = {1, 2, 3, 4, 5};
string[ ] names = {"Matt", "Joanne", "Robert"};

Look at the Collections classes too as they have more power and are generally nice (IMO)

7 Likes

Awasome dude...You list out the whole string arrays

thanks,

Or use lists (List myList = new List()) to have some more dynamic options on the fly. (using System.Collections.Generic).

2 Likes

Just to let you know, there is something called list where you can dynamically add and remove objects. List works very well in cases where you do not know how many objects you'll need instead of having a huge array since arrays are "static" and cant get their's size change other than copying the whole array which is a huge performance lost! - Good practice (from what i learned from OOP); Only use arrays if you always have a static size that and you use all the spaces, otherwise keep to list.

The problem with list is the order of elements will constantly change. Or the size will change. In most cases, using a standard container is the best way to go.

What? The order of elements will change? Never seen that happening! Why would they do that? (It may be you are right, it's a sincere question: When would they do that?)

[quote=“SubZeroGaming_1”, post:6, topic: 407413]
The problem with list is the order of elements will constantly change.
[/quote]
Unless you are implementing your own List<> system, this doesn’t happen. Ever. The reason for this is that List is built on top of a standard array.

[quote=“SubZeroGaming_1”, post:6, topic: 407413]
Or the size will change. In most cases, using a standard container is the best way to go.
[/quote]
The size only changes when you add or remove items to/from the List using .Add() or .Remove(). The Count property always returns the number of existing items in the List. When adding to the List, it checks to see if the current underlying array has a sufficient size to hold the new item, if not, it creates a new, larger array and copies the items to it. Then it adds the item to the new array.

More often than not, the functionality of List is what you’ll need anyways. And if you initialize the List correctly, it performs the same as a standard array as far as access times go (O(1) for accessing an element via index).