Tribool implementation in C #

I am trying to implement the Tribool type using http://www.boost.org/doc/libs/1_41_0/doc/html/tribool.html as a reference.

I use structure as it is a primitive type and should not be extensible. I know that there are three types of Tribools: True, False, and Unknown, and the default constructor should provide a False Tribool. My question is: what data type do I set to True, False, and Unknown to? Right now I have:

struct Tribool
{
    //True, False, and Unknown public constants
    public static readonly Tribool TRUE, FALSE, UNKNOWN;

    //Constructors
    public Tribool()
    {
        Tribool = FALSE; //use ValueType instead?
    }

but I'm not sure if this is correct, since it looks like I'm just installing Tribool for another Tribool. Should I use ValueType instead? It appeared when I was typing on VS, and that sounds reasonable, but I could not find much information about this from Google.

, Tribool bools, , "true" "false" . ? , bool?

!

: , , . bools, , .

+3
3
bool?

. ? , # "" bool . , , , bool .

: ValueType, .

bool? (.. ), enum (, byte , int )

public struct Tribool : IEquatable<Tribool> {
    public static Tribool True { get { return new Tribool(true); } }
    public static Tribool False { get { return new Tribool(false); } }
    public static Tribool Unknown { get { return new Tribool(); } }
    enum TriboolState { Unknown = 0, True = 1, False = 2 }

    private readonly TriboolState state;
    public Tribool(bool state) {
        this.state = state ? TriboolState.True : TriboolState.False;
    }
    // default struct ctor handles unknown
    public static bool operator true(Tribool value) {
        return value.state == TriboolState.True;
    }
    public static bool operator false(Tribool value) {
        return value.state == TriboolState.False;
    }
    public static bool operator ==(Tribool x, Tribool y) {
        return x.state == y.state;
    }
    public static bool operator !=(Tribool x, Tribool y) {
        return x.state != y.state; // note: which "unknown" logic do you want?
                                   // i.e. does unknown == unknown?
    }
    public override string ToString() {
        return state.ToString();
    }
    public override bool Equals(object obj) {
        return (obj != null && obj is Tribool) ? Equals((Tribool)obj) : false;
    }
    public bool Equals(Tribool value) {
        return value == this;
    }
    public override int GetHashCode() {
        return state.GetHashCode();
    }
    public static implicit operator Tribool(bool value) {
        return new Tribool(value);
    }
    public static explicit operator bool(Tribool value) {
        switch (value.state) {
            case TriboolState.True: return true;
            case TriboolState.False: return false;
            default: throw new InvalidCastException();
        }
    }
}
+7

bool?, ?

+7

What happened to Nullable<bool>?

+2
source

Source: https://habr.com/ru/post/1730824/


All Articles