Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
out
parameter
method

What is the 'out' parameter in C#?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method.

The out keyword must be explicitly declared in the method’s definition​ as well as in the calling method.

svg viewer

Code

The following code snippet demonstrates the usage of the out parameter to pass variables by reference:

using System;
class HelloWorld
{
public static void Add(out int num1, out int num2)
{
num1 = 30;
num1 += 1;
num2 = 40;
num2 += 1;
}
static void Main()
{
// Declare two without assigning a value.
int num1;
int num2;
// Call the Add method and pass it as an out parameter.
Add(out num1, out num2);
Console.WriteLine("Num1: {0}", num1);
Console.WriteLine("Num2: {0}", num2);
}
}

Note that this is a way for a method to “return” multiple values. There is no explicit return value, but num1 and num2 are both updated inside the method, and their updated values are reflected outside the method.

RELATED TAGS

c#
out
parameter
method
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring