C# provides out keyword to pass arguments as out-type. It is like reference-type, except that it does not require variable to initialize before passing. We must use out keyword to pass argument as out-type. It is useful when we want a function to return multiple values.
C# Out Parameter Example 1
- using System;
- namespace OutParameter
- {
- class Program
- {
-
- public void Show(out int val)
- {
- int square = 5;
- val = square;
- val *= val;
- }
-
- static void Main(string[] args)
- {
- int val = 50;
- Program program = new Program();
- Console.WriteLine("Value before passing out variable " + val);
- program.Show(out val);
- Console.WriteLine("Value after recieving the out variable " + val);
- }
- }
- }
Output:
Value before passing out variable 50
Value after receiving the out variable 25
The following example demonstrates that how a function can return multiple values.
C# Out Parameter Example 2
- using System;
- namespace OutParameter
- {
- class Program
- {
-
- public void Show(out int a, out int b)
- {
- int square = 5;
- a = square;
- b = square;
-
- a *= a;
- b *= b;
- }
-
- static void Main(string[] args)
- {
- int val1 = 50, val2 = 100;
- Program program = new Program();
- Console.WriteLine("Value before passing \n val1 = " + val1+" \n val2 = "+val2);
- program.Show(out val1, out val2);
- Console.WriteLine("Value after passing \n val1 = " + val1 + " \n val2 = " + val2);
- }
- }
- }
Output:
Value before passing
val1 = 50
val2 = 100
Value after passing
val1 = 25
val2 = 25
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.