Reputation: 41
I'm a long time C programmer but new to C#. I want to declare an object then creating an array of that object filling it statically (I have a very large table to enter). For example
class MyObject {
int i1;
string s1;
double d1;
};
static MyObject[] myO = new MyObject {{1,"1",1.0}, {2,"2",2.0}};
This doesn't work but you get the idea. Any help appreciated.
Upvotes: 4
Views: 34843
Reputation: 1099
I see a few things wrong here. Firstly all your variables are private. Secondly you are not calling a constructor.
class MyObject
{
public MyObject(int i1, string s1, double d1)
{
this.i1 = i1;
this.s1 = s1;
this.d1 = d1;
}
int i1;
string s1;
double d1;
};
static MyObject[] objects = new MyObject[] { new MyObject(1, "2", 3), new MyObject(1, "2", 3) };
Upvotes: 1
Reputation: 2441
You'll have to initialize the array with new object instances.
class MyObject
{
int i1;
string s1;
double d1;
public MyObject(int i, string s, double d)
{
i1 = i;
s1 = s;
d1 = d;
}
};
static MyObject[] myO = new MyObject[] {
new MyObject(1, "1", 1.0),
new MyObject(2, "2", 2.0)
};
Unfortunately there is no way to specify custom initializers like they are for arrays of built-in types or dictionaries. For (future) reference of what I mean:
int[] arr = { 1, 2, 3, 4 };
var list = new List<string> { "abc", "def" };
var dict = new Dictionary<string, int> { { "abc", 1 }, { "def", 2 } };
Upvotes: 3
Reputation: 6628
It is exactly what you want but you can achieve your goal with following code:
class MyObject
{
public int i1;
public string s1;
public double d1;
};
static MyObject[] myO = new[] { new MyObject { i1=1, s1="1", d1=1.0 }, new MyObject { i1=2, s1="2", d1=2.0 } };
Upvotes: 1
Reputation: 74267
Try
class Foo
{
public static Widget[] Widgets { get ; private set ; }
static Foo()
{
Widgets = new Widget[]{ new Widget(1) , new Widget(2) , ... } ;
}
}
Upvotes: 0
Reputation: 86718
Assuming you have public fields/properties on your class:
class MyObject
{
public int i1 { get; set; }
public string s1 { get; set; }
public double d1 { get; set; }
} // note: no semicolon needed here
static MyObject[] myO = { new MyObject { i1 = 1, s1 = "1", d1 = 1.0 },
new MyObject { i1 = 2, s1 = "2", d1 = 2.0 },
};
Upvotes: 14
Reputation: 87228
You'll need to instantiate the objects in the array:
static MyObject[] myO = new MyObject
{
new MyObject { i1 = 1, s1 = "1", d1 = 1.0 },
new MyObject { i1 = 2, s1 = "2", d1 = 2.0 },
};
Upvotes: 2
Reputation: 887453
You need to fill the array with object instances.
Create a constructor that takes parameters, then write
new MyObject[] { new MyObject(a, b, c), new MyObject(d, e, f) }
Upvotes: 3