.NET/C#
  • ASP.NET Core Overview
  • ASP.NET Core API tutorial
    • How to create ASP.NET Core C# API tutorial
      • launchSettings
      • Install swagger
        • Swagger best practices
      • Run the app
      • Fix CORS problem
      • Add AutoMapper
      • Add JWT reference
      • Add .gitignore
      • Basic structure & EF Core
      • AddSingleton
    • Loading Related Entities
  • Unit test controller logic in ASP.NET Core
    • Unit testing controllers
  • .NET Q&A
    • dotnet try
    • LINQ
      • LINQ Query Syntax
      • Lambda Expression
      • Standard Query Operators
  • .NET C# Interview questions
    • C# - .NET interview questions and answers [Part 1]
    • C# - .NET interview questions and answers [Part 2]
    • C# Interview questions [Part 3] General questions
  • C#
    • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • Project architecture
    • C# Advanced review
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Ref vs Out
      • Task
        • TaskFactory Class
  • MySQL
    • MySQL Lerning
      • SELECT
      • ORDER BY
      • WHERE
      • DISTINCT
      • IN
      • BETWEEN
      • Join
      • INNER JOIN
      • LEFT JOIN
      • RIGHT JOIN
      • GROUP BY
      • Subquery
      • UNION
    • Stored Procedures
      • CREATE PROCEDURE
  • Versioning API, MongoDB and ci-cd
    • Create a web API with ASP.NET Core and MongoDB
    • REST API versioning with ASP.NET Core
    • Design a CI/CD pipeline using Azure DevOps
      • Create a CI/CD pipeline for GitHub repo using Azure DevOps Starter
  • TFS & TFCV
    • What is Team Foundation Version Control
      • Develop and share your code in TFVC using Visual Studio
      • Suspend your work and manage your shelvesets
    • Newtonsoft Json.NET
      • Serializing and Deserializing JSON
  • MS-SQL
    • Quick tutorial
      • Add new column to a table
      • LEFT/RIGHT Reverse operator
      • Dates (Transact-SQL)
      • CAST and CONVERT (Transact-SQL)
      • Types of JOIN
      • Our first Left Outer Join
      • CROSS JOIN
Powered by GitBook
On this page
  • Out keyword
  • Calling a method with an out argument
  • Ref keywork

Was this helpful?

  1. C#
  2. C# Advanced review

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.

PreviousEventsNextTask

Last updated 4 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