C
C#3mo ago
PowerZox

Parameterless constructor in struct

public struct MyStruct
{
public int id;
static int count = 0;

public MyStruct() //Not allowed?
{
id = count++;
}
}
public struct MyStruct
{
public int id;
static int count = 0;

public MyStruct() //Not allowed?
{
id = count++;
}
}
Then public MyStruct[] myStruct = new MyStruct[100]; should call the MyStruct() constructor 100 times. How can I do this?
8 Replies
Pobiega
Pobiega3mo ago
XY problem if I ever saw one, but you'd need count to be static for this to work and even so, I dont think that array construction would work the way you expect anyways
PowerZox
PowerZoxOP3mo ago
yeah I made a mistake but it won't let me edit the body of the post
Cattywampus
Cattywampus3mo ago
why you abandoned your previous but almost similar post and make a new one, instead?
PowerZox
PowerZoxOP3mo ago
The title makes more sense in this one and is more explanatory
Anton
Anton3mo ago
you need a factory the factory should have the count and assign the id if you're doing the same for all types, all the more reason for it to be implemented separately
jcotton42
jcotton423mo ago
Array elements are always created using the default value for the element’s type. Which does not involve the zero-param ctor.
PowerZox
PowerZoxOP3mo ago
Ah ok I see Thank you I will look into this
Petris
Petris3mo ago
there is an Array.Initialize for this though

Did you find this page helpful?