.NET Course
  • Welcome developers
  • LINQ
    • Advanced c# overview
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Anonymous Types
      • Ref vs Out
      • Task
      • TaskFactory
      • Asynchronous programming with async and await
      • Abstract class VS Interface
      • Inheritance, Composition and Aggregation in C#
    • LINQ Tutorial
      • Loading Related Entities
      • Lambda Expression
      • Standard Query Operators
    • Testing ASP.NET Core
      • Implementing unit tests for ASP.NET Core Web APIs
    • Software development principles
      • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • SOLID: The First 5 Principles of Object Oriented Design
  • Helping links
    • SonarQube installation and tutorial for .net core projects
  • C# .NET Interview Questions
    • Ultimate C# Interview questions
      • Part 4
      • Part 3
      • Part 2
      • Part 1
  • Unit test .NET Core xUnit & MOQ
    • Content
      • Snippets
      • Traits
Powered by GitBook
On this page
  • Out keyword
  • Calling a method with an out argument
  • Ref keywork

Was this helpful?

  1. LINQ
  2. Advanced c# overview

Ref vs Out

Out keyword

The out is a keyword in C# which is used for passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property.

// C# program to illustrate the 
// concept of out parameter 
using System; 
  
class GFG { 
  
    // Main method 
    static public void Main() 
    { 
  
        // Declaring variable 
        // without assigning value 
        int G; 
  
        // Pass variable G to the method 
        // using out keyword 
        Sum(out G); 
  
        // Display the value G 
        Console.WriteLine("The sum of" +  
                " the value is: {0}", G); 
    } 
  
    // Method in which out parameter is passed 
    // and this method returns the value of 
    // the passed parameter 
    public static void Sum(out int G) 
    { 
        G = 80; 
        G += G; 
    } 
} 
// Output
The sum of the value is: 160

Another example can be:

int initializeInMethod;
OutArgExample(out initializeInMethod);
Console.WriteLine(initializeInMethod);     // value is now 44

void OutArgExample(out int number)
{
    number = 44;
}

You can't use the in, ref, and out keywords for the following kinds of methods:

  • The out keyword cannot be used on the first argument of an extension method.

  • The ref keyword cannot be used on the first argument of an extension method when the argument is not a struct, or a generic type not constrained to be a struct.

  • The in keyword cannot be used unless the first argument is a struct. The in keyword cannot be used on any generic type, even when constrained to be a struct.

Calling a method with an out argument

string numberAsString = "1640";

int number;
if (Int32.TryParse(numberAsString, out number))
    Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
    Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
//       Converted '1640' to 1640
string numberAsString = "1640";

if (Int32.TryParse(numberAsString, out int number))
    Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
    Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
//       Converted '1640' to 1640

Ref keywork

The ref is a keyword in C# which is used for passing the arguments by a reference. Or we can say that if any changes made in this argument in the method will reflect in that variable when the control return to the calling method. The ref parameter does not pass the property.

using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // Assign string value 
        string str = "Geek"; 
  
        // Pass as a reference parameter 
        SetValue(ref str); 
  
        // Display the given string 
        Console.WriteLine(str); 
    } 
  
    static void SetValue(ref string str1) 
    { 
  
        // Check parameter value 
        if (str1 == "Geek") { 
            Console.WriteLine("Hello!!Geek"); 
        } 
  
        // Assign the new value 
        // of the parameter 
        str1 = "GeeksforGeeks"; 
    } 
} 
// Output
Hello!!Geek
GeeksforGeeks

Difference between Ref and Out keywords

ref keyword

out keyword

It is necessary the parameters should initialize before it pass to ref.

It is not necessary to initialize parameters before it pass to out.

It is not necessary to initialize the value of a parameter before returning to the calling method.

It is necessary to initialize the value of a parameter before returning to the calling method.

The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter.

The declaring of parameter through out parameter is useful when a method return multiple values.

When ref keyword is used the data may pass in bi-directional.

When out keyword is used the data only passed in unidirectional.

PreviousAnonymous TypesNextTask

Last updated 3 years ago

Was this helpful?

Async methods, which you define by using the modifier.

Iterator methods, which include a or yield break statement.

In addition, have the following restrictions:

In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the method, which attempts to convert a string to a number.

Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration. This produces more compact, readable code, and also prevents you from inadvertently assigning a value to the variable before the method call. The following example is like the previous example, except that it defines the number variable in the call to the method.

async
yield return
extension methods
Int32.TryParse
Int32.TryParse