Illustration of Operator Keywords (true, false) with Examples in C# (C Sharp)In this article you will review the purpose and usage of two operator keywords namely true and false. Most of you might have used true and false literals for assigning Boolean values and for performing conditional checks. In addition to that, you will learn about overloading true and false operators in this article. In general, both true and false can be classified as:
literals You will analyze about each of these in detail. Literals - true, false: These literals refer to the true and false keywords that you commonly use to represent the corresponding Boolean values. Here is a simple example: class sampleClass
{ Output of
this code will be: In this example, you return true if the number is even. If it is odd, you display false. To achieve this functionality, in checkEven( ) method you assign the retval to either true or false based on the conditional check. These true and false values that you directly represent in the code are the literals with which you represent Boolean values. Operators true, false: Apart from
assigning the values true and false, you might also be performing conditional
checks wherein the conditions will be evaluated to either one of these
values. Here is a very simple example for such conditional checks: condition1 is true An if-condition will generally include expressions which evaluate to a Boolean value. In this example, you dont have any expression, but you just mention condition1 inside if-condition instead of an expression. But this is legal because the statement: if(condition1) will be interpreted as: if(condition1 == true) However this flexibility is available only for Boolean types. Check the following example: class sampleClass
{ This is invalid and it will end up in error. An if-condition can include a single variable name or a condition if and only if the variable or condition evaluates to a Boolean value. Mostly all of you know that the above example is incorrect. But to your surprise, you can make the above example legally correct and working. To do that, you have to overload the true and false operators inside your class. Here is a modified example: class sampleClass
{ Now the code will work successfully and its output will be: obj evaluates to true. objs data is even. This is because, when you specify the object obj in the if-condition, the objects overloaded true operator will be triggered. When you are overloading true and false operators, following guidelines have to be followed: You
should overload both true and false operators and not just one of them. Also note that, you can code similar logic in do, while, for statements as well.
|