Advertisement
Advertisement
//C# Example of out parameter
using System;
class A
{
//Defining the method Update() to update to the passed value type(int)
//by using the out parameter
void Update(out int i)
{
i = 30;
}
//Defining the Main() method
public static void Main(String[] ar)
{
//A local variable
int a = 20;
//Creating an object of A class
A ob = new A();
//Printing the value of local variable,a
//Before calling the Update() method
Console.WriteLine("Before calling the Update() method, the value in a is : " + a);
//The Update() method is called and passed a value type(int) by reference
//by using the out parameter
ob.Update(out a);
//Printing the value of local variable,a
//After calling the Update() method
Console.WriteLine("Afrer calling the Update() method, the value in a is : " + a);
}
}
Before calling the Update() method, the value in a is : 20
Afrer calling the Update() method, the value in a is : 30
//Defining the method Update() to update to the passed value type(int)
//by using the out parameter
void Update(out int i)
{
i = 30;
}
Also, you can see in the code just above, before we could use the out parameter, i,
in the called Update() method,
it is assigned a value 30, because the declared out parameter in the called method is considered
unassigned i.e. it contains no value, hence, it must be assigned a value.Advertisement
//C# Example of out parameter to return more than one value from the called method
using System;
class A
{
//Defining the method Update() to update to the passed value type(int)
//by using the out parameter
void Math_Calc(int value, out float remainder, out int quotient)
{
remainder = value%10;
quotient = value/10;
}
//Defining the Main() method
public static void Main(String[] ar)
{
//local variables
int q, a = 20;
float r;
//Creating an object of A class
A ob = new A();
//The Update() method is called and passed two value types, r(int) and q(float), by reference
//by using the out parameter
ob.Math_Calc(a, out r, out q);
//Printing the value of local variable, r and q
//After calling the Math_Calc() method
Console.WriteLine("The remainder after dividing {0} by {1}: {2}", a, 10 , r);
Console.WriteLine("The quotient after dividing {0} by {1}: {2}", a, 10, q);
}
}
The remainder after dividing 20 by 10: 0
The quotient after dividing 20 by 10: 2
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement