{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\nExample of pass by value:");
Console.WriteLine("-------------------------");
int Var1 = 1;
ValueFunction(Var1);
//Var1 value remains intact, ValueFunction() processes Var1
//and changes its value but original value remains the same
Console.WriteLine("Original value of Var1 remains the same");
Console.WriteLine("Var1: {0}", Var1); // 1
Console.WriteLine("\nExample of ref keyword:");
Console.WriteLine("-----------------------");
int Var2 = 2;
RefFunction(ref Var2);
Console.WriteLine("Original value of Var2 is now modified.");
Console.WriteLine("Var2: {0}", Var2); // 2
Console.WriteLine("\nExample of out keyword:");
Console.WriteLine("-----------------------");
int Var3; //not initialized, even if initialized, value of out variable depends upon processed value in
int y = OutFunction(out Var3); // outFunction will return the value of Var3
Console.WriteLine("Value of out Var3 by OutFunction: {0}", Var3); // 3
Console.WriteLine("Value returned by OutFunction: {0}", y); // 4
Console.WriteLine("\nExample of param keyword:");
Console.WriteLine("-------------------------");
int Var4;
ParamsFunction(out Var4, 2, 3, 4, 9);
Console.WriteLine("Sum of 4 numbers: {0}", Var4);
ParamsFunction(out Var4, 2, 3, 4, 5, 8, 9); // no. of parameters changed
Console.WriteLine("Sum after no. of parameters changed");
Console.WriteLine("Sum of 6 numbers: {0}", Var4);
Console.ReadKey();
}
public static void ValueFunction(int x)
{
Console.WriteLine("Before processing value of Var1 is {0}", x);
x = x + 1;
Console.WriteLine("Inside ValueFunction, value of Var1 is changed to {0}", x);
Console.WriteLine("But this change is local to the ValueFunction function.");
}
public static void RefFunction(ref int x)
{
Console.WriteLine("Before processing, value of Var2 is {0}", x);
x = x + 1;
Console.WriteLine("Inside RefFunction, value of Var2 is changed to {0}", x);
}
public static int OutFunction(out int x)
{
x = 2; //local variable
x++; // value increased by 1
return 4;
}
public static void ParamsFunction(out int res,
params int[] input)
{
res = 0;
foreach (int x in input) res += x;
}
}
}
OUTPUT
Example of pass by value:
-------------------------
Before processing value of Var1 is 1
Inside ValueFunction, value of Var1 is changed to 2
But this change is local to the ValueFunction function.
Original value of Var1 remains the same
Var1: 1
Example of ref keyword:
-----------------------
Before processing, value of Var2 is 2
Inside RefFunction, value of Var2 is changed to 3
Original value of Var2 is now modified.
Var2: 3
Example of out keyword:
-----------------------
Value of out Var3 by OutFunction: 3
Value returned by OutFunction: 4
Example of param keyword:
-------------------------
Sum of 4 numbers: 18
Sum after no. of parameters changed
Sum of 6 numbers: 31
No comments:
Post a Comment