One of my methods accepts an out int i as a parameter. I need to get the value of this variable and assign it to a local variable.
Consider the following simple console application which demonstrates the issue:.
class Program
{
static void Main(string[] args)
{
Other o = new Other();
int i = 5;
o.Demo(out i);
Console.WriteLine(i);
Console.ReadKey();
}
}
class Other
{
public void Demo(out int i)
{
// i = 10; Uncomment this to fix it (although this would not be an option)
int k = i;
}
}
I cannot assign the variable i to k (in the Demo method). Does any one have an explanation (and a work around 🙂 ).
EDIT
The above is just a contrived example of what I’m trying to do: in live, the problem is I’m re-writting code and at this stage, I’m not able to change the “out” as it’s one of the parameters of the constructor which is referenced by many, many other projects! I assume this may mean I’m stuffed
The point of
outis that you must assign a value to the passed inoutvariable.If, as your comments suggests, this is not an option, then you should not be using
outfor this.In order to assign the value, just pass in the value as normal:
Now that you have clarified your use case, I would say that you still need to refactor the
outfrom the constructor. To start, look at overloading the constructor – have an overload that you can use withoutoutand start changing the call sites to the one withoutparameters until you have cleared them all out.