0

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.

Tyler Durden
  • 1,188
  • 2
  • 19
  • 35
  • If you put some code to show what you are doing, it would help us visualize how to help you. – Guga Oct 03 '13 at 21:06
  • It's a little hard to understand what you trying to achieve. "out" means that the initialization (and value) is the responsibility of the called method. You are asking for the complete opposite. – Tormod Oct 03 '13 at 21:09
  • In the example above, I just want to ensure that if the out argument is already initialized in fun1 before fun2 call, it should keep that value intact else, it can initialize the argument in fun2. But, since it is out, fun2 has to assign a value to the parameter because of which in the first call, the value 3 is lost.\ – Tyler Durden Oct 03 '13 at 21:12
  • 1
    Just out of curiosity, did you know that int is always initialized to 0? – Jesko R. Oct 03 '13 at 21:18

2 Answers2

3

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);
Habib
  • 219,104
  • 29
  • 407
  • 436
0

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;
}
Jesko R.
  • 827
  • 10
  • 21