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.
First we examine the Employee class
. When you have complex classes, you can expose public methods (or properties) that return calculated bool
values.
IsCurrent()
, IsEmployee()
and the property Fired provide an abstraction of the internal state of the object.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
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."
We developed a class
with methods and properties returning bools. We chained these conditional expressions, with short
-circuit expressions, for the clearest code.