Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are true and false operators in C#?

Tags:

operators

c#

What is the purpose and effect of the true and false operators in C#? The official documentation on these is hopelessly non-explanatory.

like image 872
ProfK Avatar asked Mar 26 '09 16:03

ProfK


1 Answers

The true and false operators can be overloaded, to allow a class to represent its own state as true or false, for example:

public class MyClass
{
    //...
    public static bool operator true(MyClass op)
    {
        // Evaluation code...
    }

    public static bool operator false(MyClass op)
    {
        // Evaluation code...
    }
}

And you will be able to use the operator in boolean expressions:

MyClass test = new MyClass(4, 3);
if (test)
    Console.WriteLine("Something true");
else
    Console.WriteLine("Something false");

string text = test ? "Returned true" : "Returned false";
like image 170
Christian C. Salvadó Avatar answered Sep 20 '22 18:09

Christian C. Salvadó