Loser Coder
Loser Coder

Reputation: 2428

Initialize an array (string or any other data type) inside a Struct

I'm looking to do this in C#.

public struct Structure1
{ string string1 ;            //Can be set dynamically
  public string[] stringArr; //Needs to be set dynamically
}

In general, how should one initialize an array dynamically if need be? In simplest of terms, I'm trying to achieve this in C#:

  int[] array;  
  for (int i=0; i < 10; i++) 
        array[i] = i;  

Another example:

  string[] array1;  
      for (int i=0; i < DynamicValue; i++) 
            array1[i] = "SomeValue";

Upvotes: 2

Views: 5053

Answers (3)

IAbstract
IAbstract

Reputation: 19881

// IF you are going to use a struct
public struct Structure1
{
    readonly string String1;
    readonly string[] stringArr;
    readonly List<string> myList;

    public Structure1(string String1)
    {
        // all fields must be initialized or assigned in the 
        // constructor


        // readonly members can only be initialized or assigned
        // in the constructor
        this.String1 = String1

        // initialize stringArr - this will also make the array 
        // a fixed length array as it cannot be changed; however
        // the contents of each element can be changed
        stringArr = new string[] {};

        // if you use a List<string> instead of array, you can 
        // initialize myList and add items to it via a public setter
        myList = new List<string>();
    }

    public List<string> StructList
    {
        // you can alter the contents and size of the list
        get { return myList;}
    }
}  

Upvotes: 0

danyolgiax
danyolgiax

Reputation: 13086

int[] arr = Enumerable.Range(0, 10).ToArray();

update

int x=10;
int[] arr = Enumerable.Range(0, x).ToArray();

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564441

First off, your code will almost work:

int[] array = new int[10]; // This is the only line that needs changing  
for (int i=0; i < 10; i++) 
    array[i] = i; 

You could potentially initialize your arrays within your struct by adding a custom constructor, and then initialize it calling the constructor when you create the struct. This would be required with a class.

That being said, I'd strongly recommend using a class here and not a struct. Mutable structs are a bad idea - and structs containing reference types are also a very bad idea.


Edit:

If you're trying to make a collection where the length is dynamic, you can use List<T> instead of an array:

List<int> list = new List<int>();
for (int i=0; i < 10; i++) 
    list.Add(i);

// To show usage...
Console.WriteLine("List has {0} elements.  4th == {1}", list.Count, list[3]); 

Upvotes: 3

Related Questions