17

I would like to create an object array in C# of undefined length and then populate the array in a loop like so...

    string[] splitWords = message.Split(new Char[] { ' ' });

    Word[] words = new Word[];
    int wordcount = 0;
    foreach (string word in splitWords)
    {
        if (word == "") continue;
        words[wordcount] = new Word(word);
        wordcount++;
    }

However, I get the error... "Array creation must have array size or array initializer"

I'm doing a lot more logic in the foreach loop that I've left out for brevity.

1
  • 1
    Need you use an array? Doing this sort of thing with a List is often a lot easier - and can be more performant (in my experience anyway). Commented Jun 21, 2009 at 0:51

8 Answers 8

51

What you want to do is create:

List<Word> words = new List<Word>();

and then:

words.Add(new Word(word));

And finally when the loop is done if you need an array:

words.ToArray();
Sign up to request clarification or add additional context in comments.

Comments

10

If you're using C# 3.5, you can just do the following.

var words = message
  .Split(new char[]{' '}) 
  .Where(x => x != "")
  .Select(x => new Word(x))
  .ToArray();

2 Comments

If there's not a LINQ solution to your problem, you're not trying hard enough :) Nice one.
Good stuff. A note, using StringSplitOptions.RemoveEmptyEntries as your second Split() parameter would eliminate the Where() call. Although it's longer, it saves another loop through the string array.
7

You can't create an array of undefined length. This is where you'd use a generic List.

List<Word> words = new List<Word>();

Comments

1

A friendly note, you can pass option to split to ignore empty entries. Assuming no other logic to prune out entries you can preinitialize your array like so:

string[] splitWords = message.Split(new Char[] {' '},
  StringSplitOptions.RemoveEmptyEntries);
Word[] words = new Word[splitWords.Length];

1 Comment

Thanks, I did this based on another comment to an answer. Thanks, I had not yet discovered this option.
1

You can define a new list and convert to array...

var words = new List<Word>().ToArray();

Comments

0

Actually you may use list to populate your words first and then convert it easily to array like this:

string[] splitWords = message.Split(new Char[] { ' ' });

List<Word> words = new List<Word>();
int wordcount = 0;
foreach (string word in splitWords)
{
    if (word == "") continue;
    words.add(new Word(word));
    //wordcount++;
}

wordcount = words.count;
return words.ToArray();

Comments

0

I'm wondering why can't we just use a string variable (say x), initialize it and retrieve comma separated data in it and later use string[] variable (say y[]) and initialize it equal to x.Split(',') without having to initialize a blank array like follows:

string x = string.Empty;
string msg = "hi,how,r,u,xyz";

void Page_Load(object sender, EventArgs e)
     x = msg;
     string[] y = msg.Split(',');

I think this should work as needed but I didn't try running this so I am not sure. If someone thinks that my solution is wrong, please correct me.

Comments

-2

I solved it by using an ArrayList and then casting it to the object array after iterating...

    string[] splitWords = message.Split(new Char[] {' '});
    ArrayList wordList = new ArrayList();
    int wordcount = 0;
    foreach (string word in splitWords)
{
        if (word == "") continue;
        Word newWord = new Word(word);
        wordList.Add(newWord);
        wordcount++;
}
    Word[] words = (Word[])wordList.ToArray(typeof(Word)); 

I've heard the whole "create question/answer just to document it for others" is acceptable. Plus I'd like to hear if there are better suggestions. Thanks.

2 Comments

The other answers (ie. List<Word>) is generlaly considered better, as the ToArray() is less code, and it's type-safe (you can't accidentally put non-Words in it.
Great answer of using a generic List... not sure why I didn't think of that first. Thanks! Also, I guess putting my first guess as an "answer" was not such a good idea considering the down votes and ding to my rep! ha

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.