Home
Search
C# Bool Methods, Return True and FalseCreate methods and properties that return bools, testing for complex conditions.
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.
Return info. 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
Bool
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.
Return
Often Developers will use the "Is" prefix, to indicate the type of result. This is a convention.
Methods The methods IsCurrent(), IsEmployee() and the property Fired provide an abstraction of the internal state of the object.
Fired This property returns the value of the internal state member with the same name.
Property
C# program that returns true and false from method
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.
Home
© 2007-2021 sam allen.
see site info on the changelog.