bool Methods, Return True and FalseCreate methods and properties that return bools, testing for complex conditions.
This page was last reviewed on Dec 4, 2023.
Bool method. It is common for a C# method to return the values true and false. A method that returns bool can enhance code with greater abstraction.
Returning true and false from a method is a way to improve the object-orientation of your application. Programs with boolean methods can be easier to understand.
true, false
Example code. First we examine the Employee class. When you have complex classes, you can expose public methods (or properties) that return calculated bool values.
Note Developers will use the "Is" prefix, to indicate the type of result. This is a convention.
Here The methods IsCurrent(), IsEmployee() and the property Fired provide an abstraction of the internal state of the object.
Info The Fired property returns the value of the internal state member with the same name.
using System; class Employee { bool _fired = false; bool _hired = true; int _salary = 10000; public bool IsCurrent() { return !this._fired && this._hired && this._salary > 0; } public bool IsExecutive() { return IsCurrent() && this._salary > 1000000; } public bool Fired { get { return this._fired; } } } class Program { static void Main() { Employee employee = new Employee(); if (employee.IsCurrent()) { Console.WriteLine("Is currently employed"); } if (employee.IsExecutive()) { Console.WriteLine("Is an executive"); } if (!employee.Fired) { Console.WriteLine("Is not fired yet"); } } }
Is currently employed Is not fired yet
A discussion. The bool type is a common type to use as the return type in methods in C# programs. Often methods start with the word "Is."
And When you return boolean values, you can chain expressions with logical "AND" and "OR."
Summary. We developed a class with methods and properties returning bools. We chained these conditional expressions, with short-circuit expressions, for the clearest code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 4, 2023 (edit).
© 2007-2024 Sam Allen.