Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Convert from bool to bool*

I need to do use a specific method to get a job done - it cannot be any other method or assembly. The method takes the following parameters:

void method(bool* isOn) {/* Some code... */}

I try to use false for the the parameter 'isOn', but Visual Studio tells "Argument 1: cannot convert from type 'bool' to 'bool*'".

How do I convert/use bool* so that it will act appropriately?

Thanks in advance.

Edit: This is not a duplicate of Usefulness of bool* in C# because I am asking specifically about a conversion from a pointer to a type and a type itself. Also, the thread mentioned asks for the uses of bool*, but does not directly answer my question.

like image 559
Scott Avatar asked Mar 14 '23 08:03

Scott


2 Answers

bool * is a pointer to a variable of type bool, not the bool value type. Meaning what you need to pass is the memory reference to a Boolean variable, not the boolean value type itself:

https://msdn.microsoft.com/en-us/library/z19tbbca.aspx

When you call the method, what you should be able to do is as follows:

bool isOn=false;

method(&isOn);   

& address operator returns the memory address reference that the parameter appears to be requiring.

https://msdn.microsoft.com/en-us/library/sbf85k1c.aspx

Note, you may need to use unsafe context/compiler options for this to work, but assume you are already from what you've said.

like image 28
Daniel Lesser Avatar answered Mar 15 '23 22:03

Daniel Lesser


You cannot pass false, because constants do not have an address.

In order to pass a pointer to false, make a variable, set it to false, and use & operator to take variable's address:

unsafe class Program {

    static void foo(bool* b) {
        *b = true;
    }

    static void Main(string[] args) {
        bool x = false;
        Console.WriteLine(x); // Prints false
        foo(&x);
        Console.WriteLine(x); // Prints true
    }

}

Note how the method is allowed to change the variable through a pointer.

like image 94
Sergey Kalinichenko Avatar answered Mar 15 '23 21:03

Sergey Kalinichenko