Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create c# object array of undefined length?

Tags:

arrays

c#

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.

like image 390
Lyndal Avatar asked Jun 21 '09 00:06

Lyndal


People also ask

What is create () in C?

General description. The function call: creat(pathname,mode) is equivalent to the call: open(pathname, O_CREAT|O_WRONLY|O_TRUNC, mode); Thus the file named by pathname is created, unless it already exists. The file is then opened for writing only, and is truncated to zero length.

How do you create a file in C?

To create a file in a 'C' program following syntax is used, FILE *fp; fp = fopen ("file_name", "mode"); In the above syntax, the file is a data structure which is defined in the standard library. fopen is a standard function which is used to open a file.

What is read () in C?

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file.

What is open in C?

open: Used to Open the file for reading, writing or both. Syntax in C language #include<sys/types.h> #include<sys/stat.h> #include <fcntl.h> int open (const char* Path, int flags [, int mode ]);


1 Answers

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();
like image 123
jasonh Avatar answered Oct 27 '22 01:10

jasonh