Use out Parameter
using System; class Program/*from ww w . ja v a 2 s . c o m*/ { static void Change(out int x) { x = 25; x = x * 2; Console.WriteLine("Inside Change(), myVariable is {0}", x);//50 } static void Main(string[] args) { int myVariable; Change(out myVariable); Console.WriteLine("Inside Main(), myVariable={0}", myVariable);//50 } }
The value change is reflected in both Main() and ChangeMe()).
In this program, we did not initialize myVariable before it was passed to the ChangeMe() method.
For the out parameter, this initialization is not mandatory.
But for ref, it is a must.
We needed to assign a value before it came out of the function; for the out parameter, it is required.