Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Inherit from Boolean?

(how) can I Inherit from Boolean? (Or make my class comparable to Boolean with '=' Operator)

class MyClass : Boolean
{
    public MyClass()
    {
        this = true;
    }
}
class Program
{
    public Program()
    {
        MyClass myClass = new MyClass();
        if(myClass == true)
            //do something...
        else
            //do something else...
    }
}
like image 305
Reini Avatar asked Nov 30 '22 08:11

Reini


2 Answers

You can't. System.Boolean is a struct, and you can't derive from structs.

Now, why do you want to do so, exactly? What's the bigger purpose?

You could include an implicit conversion operator from your class to bool, but personally I wouldn't. I would almost always prefer to expose a property, so you'd write:

if (myValue.MyProperty)

... I think that keeps things clear. But if you could give us more of the real context, we may be able to give more concrete advice.

like image 54
Jon Skeet Avatar answered Dec 02 '22 22:12

Jon Skeet


Simple example:

public class MyClass {
    private bool isTrue = true;

    public static bool operator ==(MyClass a, bool b)
    {
        if (a == null)
        {
            return false;
        }

        return a.isTrue == b;
    }

    public static bool operator !=(MyClass a, bool b)
    {
        return !(a == b);
    }
}

somewhere in code you can compare your object with boolean value:

MyClass a = new MyClass();
if ( a == true ) { // it compares with a.isTrue property as defined in == operator overloading method
   // ...
}
like image 27
meir Avatar answered Dec 02 '22 22:12

meir