C #: Inherit from booleans?

(how) can be inherited from booleans? (Or make my class comparable to a boolean using the "=" 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...
    }
}
+3
source share
6 answers

A 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 the code you can compare your object with a boolean value:

MyClass a = new MyClass();
if ( a == true ) { // it compares with a.isTrue property as defined in == operator overloading method
   // ...
}
+5
source

You can not. System.Booleanis a structure, and you cannot get a structure.

Now, why do you want to do this, for sure? What is the big goal?

You can enable the implicit conversion operator from your class to bool, but I personally wouldn’t. I almost always prefer to exhibit property, so you should write:

if (myValue.MyProperty)

... , . , .

+10

, :

class MyClass {
  public bool Value { get; set; }
  public MyClass() {
    Value = true;
  }
  public static implicit operator bool(MyClass m) {
    return m != null && m.Value;
  }
}

class Program {
  public static void Main() {
    var myClass = new MyClass();
    if (myClass) { // MyClass can be treated like a Boolean
      Console.WriteLine("myClass is true");
    }
    else {
      Console.WriteLine("myClass is false");
    }
  }
}

, :

if (myClass) ...

:

if (myClass == true) ...
+2

, - , , .

http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return a.x == b.x && a.y == b.y && a.z == b.z;
}

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

( " ..." ), ==. , .

0

if, operator true operator false ( & |, && ||.) ( VB)

To answer more, I would have to know what you are trying to do (in other words, why not just use it booldirectly?)

0
source

All Articles