Define custom struct and populate

  • Thread starter Thread starter stuie_norris
  • Start date Start date
S

stuie_norris

Hi Readers,

I wish to define a const structure and populate it with data.

I have tried implement this in the example below, but keep on getting
"Array initializers can only be used in a variable or field
initializer. Try using a new expression instead."

What is wrong with what I am doing?

Thanks

Stuart

using System;
using System.Collections.Generic;
using System.Text;

namespace structexamp
{
class Program
{
static void Main(string[] args)
{
}

public struct myinfo
{
String code;
int num;
}

myinfo[] myInfo = {{"STR1", 1},{"STR2", 2}};
}
}
 
Try

static void Main(string[] args)
{

CARS[] array = { new CARS("Honda", 0), new CARS("Toyota",
0) };
int i = 0;
}

public class CARS
{
string sText;
int x;

public CARS(string sText, int x)
{
this.sText = sText;
this.x = x;

}
};
 
Thanks for that.

A further question. How do you access the fields using an if
statement - say for the x field in your example?

if (array.x == 0 )

Thanks

Stuart
 
Thanks for that.

A further question. How do you access the fields using an if
statement - say for the x field in your example?

if (array.x == 0 )


You'd probably want to create a property in your new type to allow you
to get at it. You *could* make the field non-private, but I wouldn't
recommend it...

Jon
 
Back
Top