I am using a struct to pass to an unmanaged DLL as so -
[StructLayout(LayoutKind.Sequential)]
public struct valTable
{
public byte type;
public byte map;
public byte spare1;
public byte spare2;
public int par;
public int min;
public byte[] name;
public valTable()
{
name = new byte[24];
}
}
The code above will not compile because VS 2005 will complain that "Structs cannot contain explicit parameterless constructors". In order to pass this struct to my DLL, I have to pass an array of struct's like so valTable[] val = new valTable[281];
What I would like to do is when I say new
, the constructor is called and it creates an array of bytes like I am trying to demonstrate because the DLL is looking for that byte array of size 24 in each dimension.
How can I accomplish this?
Struct constructors are similar to class constructors, except for the following differences:
This means that
The typical way to get around this scenario is to create a static method that will create your new instance, initialize it the way you want, and return it. This is the way it is done in .NET to get structures initialized with specific values.
ref; Structs cannot contain explicit parameterless constructors. WHY?
You can use a fixed size buffer - which I suspect you really want anyway, so as to get the data "inline" in the struct (rather than a reference to an array elsewhere).
You'll need to declare the struct as unsafe as well though.
Note that any "solution" which requires calling a static method or providing any kind of custom constructor will fail with your explicit goal of being able to create an array of these structs.
Not the cleanest fix, but you could just add a parameter and never use it?
I would recommend to write this code.
Building on Asad Butt's answer, you can create a static method to perform the work of your constructor like so:
You'll see classes in the .NET Framework following this pattern already.
Guid.NewGuid()
immediately springs to mind. There may be others.For what you need to do you really need a class I think. A struct already implements a parameterless constructor by default which is why you cant define another one.