Question

I have defined a function where one of the parameters is out. Here, when the function call is made, I pass either a an initialized or an uninitialized argument. Now, in the case of an initialized argument, how do I make the callee not change the value of the out parameter?

I cant use a ref here because sometimes I do send an uninitialized argument. Ex:

void fun1()
{

    int x = 3;
    fun2 (out x);
    int y;
    fun2(out y);

}

void fun2(out int x)
{

    ...

}

Here, I dont want the x to lose the value 3 once control goes to fun2.

Was it helpful?

Solution

From out C# - MSDN

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Since a value must be assigned to the parameter with out, you can't save the value in function. It would be better if you make a copy of the variable before calling the function. like:

int x = 1;
int backupX = x;
fun2(out x);

OTHER TIPS

Maybe I get all wrong, but this sounds like you just want to define a method like this

void caller(){
int x=5;
int y = doSomething(x);
}

int doSomething(int x){
 return x+1;
}

or in case you want a null state use:

void caller(){
int? x=5;
int y = doSomething(x);
}

int doSomething(int? x){
 if (x == null)
    return x;
 return x+1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top