learning33

I want to declare a class variable "plant" with 150 slots. I want to do this on a global( ) level in my class so I can use the variable anywhere. Then later in the code, in a method, I want to put 150 strings into these slots. I know I can do this by using:

private string[] plant = new string [150];

and later:
hand[0] = "ek";
hand[1] = "bok";
... and so on.

but is there any more convenient way

I tried using:

private string[] plant = new string [150];

and later

plant[] = {"","","","",............}

but that didn't work...



Re: Visual C# Language Assigning lot's of string into an array after it has been declared

theTroll527

You can only use the plant[] = {...} syntax on declaration, you can not use it later in code.

So you have to do it the first way or do this.

private string[] plant = new string [150];

later do this...
string[] temp_plants = {...//your plants here};
for(int index = 0; index < plant.Length; index++)
{
plant[index] = temp_plants[index];
}

If you want your plant member to be avalible anywhere you can always make it static.

theTroll





Re: Visual C# Language Assigning lot's of string into an array after it has been declared

learning33

Very clever solution. Thanks!




Re: Visual C# Language Assigning lot's of string into an array after it has been declared

theTroll527

You say clever, I say hack. :)

If you have that many, I would really suggest either loading from a file or internal resource if it will never change, much easier to maintain. But that was not your question.

theTroll




Re: Visual C# Language Assigning lot's of string into an array after it has been declared

learning33

Thanks. I'll keep that in mind. I'm not redy for that yet I think, but I'll try to learn with time.




Re: Visual C# Language Assigning lot's of string into an array after it has been declared

Bashmohandes

Why don't you use List<String> which is more efficient which is not going to reserve the memory till you add the strings





Re: Visual C# Language Assigning lot's of string into an array after it has been declared

timvw

private string[] plant = new string[] { "abc", "def", string.Empty, "ghi" };





Re: Visual C# Language Assigning lot's of string into an array after it has been declared

Figo Fei - MSFT

Hi, learning33

If you want to define an array with indefinite number of its members, you can take advantage of Generics in C#, it is a useful featrue for this purpose.

In your case, define as List<string> StringList = new List<string>();

Or use ArrayList etc..

Otherwise, check the members in System.Collections.Generic Namespace.

Thanks