C# Bool Methods, Return True and False

Create methods and properties that return bools. Test for complex conditions.

Bool method. A method returns true or false. In this way, it can enhance your code with greater abstraction. Returning true and false from a method is a way to improve the object-orientation of your application. It simplifies it.True, FalseBool

Example. Here we declare a class that has several fields, which determine its state. 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.

Tip: When you return boolean values, you can chain expressions with logical "AND" and "OR".

Fired: This property returns the value of the internal state member with the same name. Properties allow more flexibility when changing implementations.

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"); } } } Output Is currently employed Is not fired yet

Discussion. The bool type is a common type to use as the return type in methods in C# programs. The class above provides the syntax for this pattern. Next, we look at the logic regarding boolean result values and methods that return bools.

Quote: Understanding complicated boolean tests in detail is rarely necessary for understanding program flow (Code Complete).

Summary. We developed a class with methods and properties returning bools. We discussed the principles of abstraction in object-oriented programming, and researched the topic in one of the leading books about software construction.

And: We chained these conditional expressions, with short-circuit expressions, for the clearest code.

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to