"Joanna Carter [TeamB]"
Hi
struct MyStruct
{
int value = 64; // does not compile
public MyStruct()
{
value = 64; //does not compile
}
}
What do I do to create a struct so that default(MyStruct) returns a
MyStruct
with value already set to 64 ?
Joanna
Hi Joanna,
The .net framework disallows default (parameterless) constructors for
structs. I'm not sure why, but my guess is that because you can use structs
without "new", the framework cannot guarantee that the default constructor
will always be called.
Suppose the framework did allow your code to compile, then what would be the
value of "value" after the following code:
{
MyStruct struct;
Console.WriteLine("Value is {0}",struct.value);
}
The default value for int is 0, and that would be the output of the code
above, which could allow for some nasty bugs in your code. But that's only
my guess, please someone jump in if I'm wrong.
All that said, you are still allowed to write parameterized constructors,
and your code could look like:
struct MyStruct
{
int value;
public MyStruct(int initval)
{
value = initval;
}
}
Hope that helps.
By the way, it's amazing to see how many delphi dissidents I'm finding
around here. To speak the truth, all my friends who used to program in
delphi before are now converted to C#...
Cheers
Padu