out parameters
In this chapter you will learn:
Use out for int type
out
is like ref
modifier,
but when calling the method you don't have to provide
a value for the out
parameter.
An out parameter is used to pass a value out of a method. It is not necessary to give the variable used as an out parameter an initial value. An out parameter is always considered unassigned. The method must assign the parameter a value prior to the method's termination.
using System;// ja v a 2s. c om
class Point
{
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public void GetPoint(out int x, out int y)
{
x = this.x;
y = this.y;
}
int x;
int y;
}
class MainClass
{
public static void Main()
{
Point myPoint = new Point(10, 15);
int x;
int y;
myPoint.GetPoint(out x, out y);
Console.WriteLine("myPoint({0}, {1})", x, y);
}
}
The code above generates the following result.
Use out for reference type
using System;/* ja v a 2 s .c om*/
class MyClass
{
public int Val = 20;
}
class MainClass
{
static void MyMethod(out MyClass f1, out int f2)
{
f1 = new MyClass();
f1.Val = 25;
f2 = 15;
}
static void Main()
{
MyClass myObject = null;
int intValue;
MyMethod(out myObject, out intValue);
Console.WriteLine("After -- myObject.Val: {0}, intValue: {1}", myObject.Val, intValue);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Variable arguments to a method
- How to pass in array to a method with variable length parameter
- How to mix normal parameters and variable length parameter
Home » C# Tutorial » Class