Initializing an Array of Structs in C#

Initializing an Array of Structs in C#

Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

Other than that, I'd just create a constructor taking the two bits of data:

class SomeClass
{

struct MyStruct
{
private readonly string label;
private readonly int id;

public MyStruct (string label, int id)
{
this.label = label;
this.id = id;
}

public string Label { get { return label; } }
public string Id { get { return id; } }

}

static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
(new[] {
new MyStruct ("a", 1),
new MyStruct ("b", 5),
new MyStruct ("q", 29)
});
}

Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

How to initialize array of struct?

You need to use actual instances of your MyStruct, which you can create with the new keyword.

This should work...

struct MyStruct 
{
int i, j;

public MyStruct(int a, int b)
{
i = a;
j = b;
}
}

static MyStruct[] myTable = new MyStruct[3]
{
new MyStruct(0, 0),
new MyStruct(1, 1),
new MyStruct(2, 2)
};

Initialization of const array of struct

Sample code:

struct Item
{
public int a;
public string b;
};
Item[] items = {
new Item { a = 12, b = "Hello" },
new Item { a = 13, b = "Bye" }
};

Additional option to introduce parametrized constructor:

struct Item
{
public int a;
public string b;

public Item(int a, string b)
{
this.a = a;
this.b = b;
}
};
Item[] items = {
new Item( 12, "Hello" ),
new Item( 13, "Bye" )
};

As @YoYo suggested, removed new[] part.

Tricky way (for the case where new Item bothers you much)

Declare new class:

class Items : List<Item>
{
public void Add(int a, string b)
{
Add(new Item(a, b));
}
}

Then you can initialize it as:

Items items = new Items {
{ 12, "Hello" },
{ 13, "Bye" }
};

You can also apply .ToArray method of List to get an array of Items.

Item[] items = new Items {
{ 12, "Hello" },
{ 13, "Bye" }
}.ToArray();

The trick is based on collection initializers (http://msdn.microsoft.com/en-us/library/bb384062.aspx):

By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

How to initialize char array in struct

You can use a constructor for this. Look at MSDN.

struct cell
{
public cell(int size)
{
domain = new char[size];
this.Peers = Peers;
this.NumberOfPeers = NumberOfPeers;
this.assignValue = assignValue;
}
}

Array of structs example

You've started right - now you just need to fill the each student structure in the array:

struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];

for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");

arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}

Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.

Why doesn't a struct in an array have to be initialized?

As per the specification link provided by PetSerAl in the comments:

Array elements

The elements of an array come into existence when an array instance is created, and cease to exist when there are no references to that array instance.

The initial value of each of the elements of an array is the default value (Default values) of the type of the array elements.

For the purpose of definite assignment checking, an array element is considered initially assigned.

(emphasis mine).

This means that when you declare an array of T, each "cell" in the array is being initialized using default(T). For reference types default(T) returns null, but for value types default(T) returns the type default value – 0 for numbers, false for bool, and so on.

As per the Using Structs (C# Programming Guide) page:

If you instantiate a struct object using the default, parameterless constructor, all members are assigned according to their default values.

Since structs are value types, default(T) where T is a struct initializes the struct to its default value, meaning all its members will be initialized to their default values – null for reference types and whatever default value for value types.

So this line of code StructAPI[] sAPI = new StructAPI[1]; basically creates a new array of StructAPI containing a single StructAPI instance, where its mesh property is default(Mesh).

Initilize an array of struct

Add a constructor to your struct, and put new PrgStrTrans(...), on each line of the array.

Like this:

private struct PrgStrTrans_t
{
public int id;
public string name;
public string fname;

public PrgStrTrans_t(int i, string n, string f)
{
id = i;
name = n;
fname = f;
}
}

private PrgStrTrans_t[] PrgStrTrans = {
new PrgStrTrans_t(4, "test", "something"),
new PrgStrTrans_t(2, "abcd", "1234")
}

How to initialize a multi-dimensional array of structs

This code is valid C# and should do what you want:

    struct test_struct
{
double a, b, c, d, e;
public test_struct(double a, double b, double c, double d, double e)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
};

private test_struct[,] Number =
{
{

new test_struct(12.44, 525.38, -6.28, 2448.32, 632.04),
new test_struct(-378.05, 48.14, 634.18, 762.48, 83.02),
new test_struct(64.92, -7.44, 86.74, -534.60, 386.73),

},

{
new test_struct(48.02, 120.44, 38.62, 526.82, 1704.62),
new test_struct(56.85, 105.48, 363.31, 172.62, 128.48),
new test_struct(906.68, 47.12, -166.07, 4444.26, 408.62),
},
};


Related Topics



Leave a reply



Submit