I'm a little embarrassed to ask this one, since it seems so fundamental, but here goes anyway:
I'm trying to create an array of structs which I'll populate at compile-time. So I've got a struct
struct S {
string str;
int idx;
double wgt;
};
which I want to populate something like this:
S [] s = {
{ "name", 0, 1.24 },
{ "foo", 3, 3.14 },
...
{ "", 0.0, 0.0 }
};
I've tried the above and a variety of permutations, but can't figure out how to get the compiler to accept it. I can call the struct a class, but that doesn't seem to make much difference. It's a big list, and this kind of problem is not unusual in coding, so there must be a way!
Thanks for any help,
Hugh
Loading
ShankeyPosted Aug 10, 2010, 10:28 AM
Try the following code to initialize array of struct and display.
And Mark my answer as accepted if it helped you. :)
****************************************************
using System;
using System.Collections.Generic;
using System.Text;
namespace StructExample
{
public class Class1
{
public struct S
{
string str;
int idx;
double wgt;
public S(string str, int idx, double wgt)
{
this.str = str;
this.idx = idx;
this.wgt = wgt;
}
public void display()
{
Console.WriteLine("Struct values");
Console.WriteLine("str = {0}, idx = {1} , wgt = {2}", this.str , this.idx,this.wgt);
}
}
public static void Main()
{
// Compile time Initialize:
S[] arr = { new S("Array 1",1,1.5),
new S("Array 2",2,2.5),
new S("Array 3",3,3.5)};
//Display one by one
for (int i = 0; i < arr.Length; i++)
{
arr[i].display();
}
}
}
}
*************************************************
HughPosted Aug 10, 2010, 4:00 PM