C# out parameter

Description

An out argument is like a ref argument, except it:

  • Variables need not be assigned before going into the function
  • Parameters must be assigned before it comes out of the function

The out modifier is most commonly used to get multiple return values back from a method.

Syntax

out parameter has the following syntax:

methodName(out type parameter);

when calling the method

methodName(out variableName);

Example

For example:


using System;//from w  ww  . j  a  v a  2s. c o  m
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.

Example 2


using System;/*from ww w  . j a  v a  2  s  .c  o m*/

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.

Note

Like a ref parameter, an out parameter is passed by reference.

When you pass an argument by reference, you alias the storage location of an existing variable rather than create a new storage location.

In the following example, the variables x and y represent the same instance:


using System;//from w w  w  . j av  a  2 s. c  o m

class MainClass
{ 
  static int x; 

  static void Main() { Foo (out x); } 

  static void Foo (out int y) 
  { 
    Console.WriteLine (x);                // x is 0 
    y = 1;                                // Mutate y 
    Console.WriteLine (x);                // x is 1 
  } 
} 

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor