C # - convert from bool to bool *

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

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

I am trying to use false for the isOn parameter, but Visual Studio says: "Argument 1: cannot be converted from type" bool "to" bool * ".

How do I convert / use bool * so that it acts properly?

Thanks in advance.

Edit: this is not a duplicate of the bool * utility in C # , because I am specifically asking about conversion from a pointer to a type and the type itself. In addition, the thread mentioned requires the use of bool *, but does not directly answer my question.

+4
source share
2 answers

You cannot pass falsebecause constants do not have an address.

To pass a pointer to false, make a variable, set it to falseand use the operator &to accept the address of the variable:

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
    }

}

Pay attention to how to change a method using a pointer.

+4
source

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

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

When you call a method, you should be able to do the following:

bool isOn=false;

method(&isOn);   

& address operator returns a reference to the memory address required by the parameter.

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

. , /, , , , .

+3

Source: https://habr.com/ru/post/1627530/


All Articles