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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.