Overwriting Default values in C# structs
For an assignment I have to write a Tribool class in C# using a struct. There are only three possible tribools, True,开发者_StackOverflow社区 False, and Unknown, and I have these declared as static readonly. Like this:
public static readonly Tribool True, False, Unknown;
I need my default constructor to provide a False Tribool, but I'm not sure how to go about this. I've tried Tribool() { this = False; }
and Tribool() { False; }
but I keep getting a "Structs cannot contain explicit parameterless constructors" error.
The assignment specified that the default constructor for Tribool should provide a False Tribool. Otherwise, a user should not be able to create any other Tribools. I don't really know what to do at this point. Any advice would be greatly appreciated. Thanks.
Just to add a bit to Jason's answer: design your struct carefully so that the default value is meaningful. As an example, consider the Nullable<T>
struct. The desired behaviour is that when you say
Nullable<int> x = new Nullable<int>(); // default constructor
that the resulting value is logically null. How do we do that? The struct is defined something like this:
struct Nullable<T>
{
private readonly T value;
private readonly bool hasValue;
public Nullable(T value)
{
this.value = value;
this.hasValue = true;
}
...
So when the default constructor runs, hasValue is automatically set to false and value is set to the default value of T. A nullable with hasValue set to false is treated as null, which is the desired behaviour. That's why the bool is hasValue and not isNull.
As the error is telling you, you absolutely can not have a parameterless instance constructor for a struct. See §11.3.8 of the C# 3.0 language specification:
Unlike a class, a struct is not permitted to declare a parameterless instance constructor.
The language provides one for you known as the default constructor. This constructor returns the value of the struct where are fields have been set to their default value.
Now, what you could do is have the default value of the struct represent the False
value. I'll leave the details to you.
Little late to the game but, is there any reason your not using an enum?
after all if you just need a Trinary value then the struct is massive overkill
public enum Tribool{
Unknown =0,
True = -1,
False = 1
}
精彩评论