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 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.