Alex Cavanaugh
Alex Cavanaugh

Reputation: 435

How to use bool in C#

I am completely new to C# and I know this is an extremely basic question but after searching I couln't find any answers here or elsewhere on the internet. When using bool in C#, you can have parameters, and then something inside your curly brackets. I'm curious as to what parameters a boolean can have? Everywhere I look it seems that they are always either just true or false and never take parameters. For instance:

public bool TestBool(double number)
{
...some code...
}

Where I typed "some code", when would this code get used? Is it called every time the boolean evaluates to true? If anyone has any knowledge or advice on somewhere to read up on this I would really appreciate it, thanks.

Upvotes: 2

Views: 10319

Answers (3)

user1666620
user1666620

Reputation: 4808

TestBool is the name of the method.

The bool portion is the return type. - it returns either true or false depending on the logic in the method.

public means that anything that references this dll can call the method TestBool.

the (double number) portion means that the method TestBool accepts a parameter of type double, which can be used within the method.

Upvotes: 6

David Arno
David Arno

Reputation: 43254

boolis a basic true/false type that cannot take parameters. In your example, you have a function (method) that does something with a number and returns true or false (the bool) depending on the result. So it might for example be:

public bool TestBool(double number)
{
    if (number > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

However you never really need to work with true and false directly as any expression like number > 0 returns a bool itself, so your function can just be:

public bool TestBool(double number)
{
    return number > 0;
}

Upvotes: 5

Jashaszun
Jashaszun

Reputation: 9270

The bool is the return type of the method TestBool, and number is the only parameter. This means that any code that uses your function TestBool has to give it a double, and gets a bool in return.

The return type goes before the method name, and parameters go inside the parentheses after the method name.

The code inside the method can use the value of number for any calculations it needs, but must at some point return a bool value (true or false).

Upvotes: 2

Related Questions