Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro C# Get Started C# Syntax C# Output C# Comments C# Variables C# Data Types C# Type Casting C# User Input C# Operators C# Math C# Strings C# Booleans C# If...Else C# Switch C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# ref and out


Share

A Method Gets a Copy

When you pass a variable to a method, the method gets a copy of the value.

If the method changes the parameter, it only changes the copy. The original variable keeps its value:

Example

static void AddPoints(int points)
{
  points = points + 10;
  Console.WriteLine("Inside the method: " + points);
}

static void Main(string[] args)
{
  int score = 5;
  AddPoints(score);
  Console.WriteLine("After the method: " + score);
}

Try it Yourself »

Inside the method, points is 15. But score is still 5, because the method only changed its own copy.

This is usually what you want: a method cannot change your variables by mistake. But sometimes you want a method to change the original variable. For that, C# has the ref keyword.


The ref Keyword

The ref keyword passes the variable itself to the method, not a copy. When the method changes the parameter, the original variable changes too.

Write ref in two places: before the parameter type, and before the argument when you call the method:

Example

static void AddPoints(ref int points)
{
  points = points + 10;
  Console.WriteLine("Inside the method: " + points);
}

static void Main(string[] args)
{
  int score = 5;
  AddPoints(ref score);
  Console.WriteLine("After the method: " + score);
}

Try it Yourself »

Now score is 15 after the method call.

A good use of ref is a method that swaps (exchanges) the values of two variables:

Example

static void Swap(ref int a, ref int b)
{
  int temp = a;
  a = b;
  b = temp;
}

static void Main(string[] args)
{
  int x = 10;
  int y = 20;
  Console.WriteLine("Before: x = " + x + ", y = " + y);
  Swap(ref x, ref y);
  Console.WriteLine("After: x = " + x + ", y = " + y);
}

Try it Yourself »

The temp variable holds the value of a for a moment, so it is not lost when a gets the value of b.

Without ref, the method would only swap its own copies, and x and y would not change.



The out Keyword

A method can only return one value. The out keyword lets a method give back an extra value, through a parameter.

The following method shares coins between players. It returns how many coins each player gets, and it gives back the coins that are left with out:

Example

static int ShareCoins(int coins, int players, out int left)
{
  left = coins % players;
  return coins / players;
}

static void Main(string[] args)
{
  int left;
  int each = ShareCoins(17, 5, out left);
  Console.WriteLine("Each player gets " + each + " coins");
  Console.WriteLine("Coins left: " + left);
}

Try it Yourself »

17 coins shared by 5 players is 3 coins each, and 2 coins are left. The % operator gives the remainder of a division.

Like ref, you write out both in the method and in the call.

The variable left does not need a value before the call. The method must give the out parameter a value before it ends.


int.TryParse()

You will often see out in a method that is built into C#: int.TryParse().

In the User Input chapter, you used Convert.ToInt32() to convert text to a number. If the text is not a number, like "abc", the program stops with an error.

int.TryParse() tries to convert a string to an int, without stopping the program:

  • It returns true if it worked, and false if not.
  • It puts the converted number in the out variable.

Example

bool success = int.TryParse("123", out int number);
Console.WriteLine(success);  // True
Console.WriteLine(number);   // 123

Try it Yourself »

out int number creates the variable number right inside the method call, so you do not need to declare it on a line before.

Use int.TryParse() in an if statement to check the text before you use the number:

Example

string text = "abc";

if (int.TryParse(text, out int number))
{
  Console.WriteLine("The number is " + number);
}
else
{
  Console.WriteLine(text + " is not a number");
}

Try it Yourself »


ref or out?

refout
Must the variable have a value before the call?YesNo
Must the method give it a value?NoYes
Use it whenthe method should change an existing variablethe method should give back an extra value


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.