Home Backend Development C#.Net Tutorial Detailed introduction to the difference between out and ref in C# (picture and text)

Detailed introduction to the difference between out and ref in C# (picture and text)

Mar 29, 2017 am 11:53 AM

This article mainly introduces the relevant knowledge of out and ref. It has a certain reference value. Let’s take a look at it with the editor.

In order to fully understand C# out and ref, you must first clarify the following two concepts ( If you have a good grasp of value types and reference types, you can skip "1. Clarify two basic concepts")

1. Clarify two basic concepts

Value type:

Definition: Passed by value, that is, the actual parameters are passed to the formal parameters (the terms formal parameters and actual parameters are not defined here).

Storage method: Mainly in the stack.

Essence: Implemented through value transfer, copycopy form, and the Pop() and Push() methods of the call stack.

Common types: int, float, bool, enum, struct, Array, etc.

Value type example:

//主函数
 static void Main(string[] args)
 {
  //定义两个实参n1和n2,并初始化
  int n1 = 10, n2 = 20;
  Console.WriteLine("交换前n1和n2的值");
  Console.WriteLine("n1={0},n2={1}", n1, n2);//n1=10,n2=20
  Swap(n1,n2);
  Console.WriteLine("交换后n1和n2的值");
  Console.WriteLine("n1={0},n2={1}",n1,n2);//n1=10,n2=20
  Console.Read();
 }
 /// <summary>
 /// 交换两个变量的值
 /// </summary>
 /// <param name="n1">形参n1</param>
 /// <param name="n2">形参n2</param>
 static private void Swap(int t1,int t2)
 {
  int temp;
  temp =t1;
  t1 =t2;
  t2 = temp;
 }
Copy after login

Analysis: The above code is passed by value. After exchanging the two variables, the values ​​of n1 and n2 are not changed. The fundamental reason is that the value is passed through copy. Copy form without changing the original value. The picture is as follows:

1) Define variables n1 and n2, and initialize the variables. The representation in memory is roughly as follows (int n1 = 10, n2 = 20;)

CodeDebugging

is represented in memory

2) When executing the exchange variable method

Code debugging

Represented in memory

Exchange detailed steps diagram

Reference type:

Definition: Passed by address, such as a pointer in c++. In layman's terms, just think of the address as the key to the door.

Storage method: Mainly stored in the heap.

Essence: Passed by address, shared variables, one change, all changes.

Common types: String, Object, etc.

code:c++

// Cpplus.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//主函数
int _tmain(int argc, _TCHAR* argv[])
{
 void Swap(int *x, int *y);
 int n1 = 10, n2 = 20;
 printf("交换前n1和n2的值\n");
 printf("%d,%d\n", n1, n2);
 Swap(&n1,&n2);
 printf("交换后n1和n2的值\n");
 printf("%d,%d",n1,n2);
 getchar();
 return 0;
}
//交换函数
void Swap(int *x, int *y)
{
 int temp = *x;
 *x = *y;
 *y = temp;
}
Copy after login

result:

##Debugging

Schematic diagram

2. Why are out and ref introduced

It can be seen from the above analysis that value transfer It is impossible to change the value of a variable. What should I do if I want to change the value of a variable like C++?

c#Introduced out and ref to solve this problem. Therefore, both out and ref are reference types.

2. Detailed explanation of out

In one sentence: out can only enter but not exit.


//主函数
 static void Main(string[] args)
 {
  int n1, n2;
  Console.WriteLine(GetSum(out n1,out n2));
  Console.Read();
 }
 //out参数
 static public int GetSum(out int numberFirst,out int numberSecond)
 {
  numberFirst = 10;
  numberSecond = 3;
  return numberFirst + numberSecond;
 }
Copy after login

result:

out Features:

1. Both method definition and method calling must use the out keyword. (The above code is obviously easy to see)

2. out only goes out but not in, that is, it has the function of clearing the external parameters of the method. (In the above code, readers can change the values ​​of n1 and n2 arbitrarily. As long as the GetSum() method body is not changed, the output value is 13)

3. It is a reference type. (If you call it directly without defining n1 and n2 in advance, the compilation will not pass)

4. For functions with the same name, out does not exist with ref at the same time, and can be

overloaded.

//如下两个方法可以重载
public void getNumer(int num){}
public void setTime(out int num){num=10;}
//如下两个方法不能重载
public void getNumer(ref int num){num=10;}
public void setTime(out int num){num=10;}
Copy after login

3. Detailed explanation of ref

In one sentence: what goes in, comes out.

//主函数
 static void Main(string[] args)
 {
  int n1=1, n2=3;
  Console.WriteLine(refGetSum(ref n1,ref n2));
  Console.Read();

 } 
 //ref参数
 static public int refGetSum(ref int numberFirst, ref int numberSecond)
 {
  numberFirst = 10;
  numberSecond = 3;
  return numberFirst + numberSecond;
 }
Copy after login

ref特点: 

   1、方法定义和调用方法都必须显示使用ref关键字。(如上代码显然易见)

   2、ref有进有出,即可以把值传入方法体内。(如上代码,读者可以任意改变n1和n2的值)

   3、为引用类型。(直接调用而不事先定义n1和n2,编译不通过)

   4、同名函数,out不与ref同时存在,可以重载。

四、out与ref异同

主要区别,out只输出yuan'chuang,ref有进有出。

The above is the detailed content of Detailed introduction to the difference between out and ref in C# (picture and text). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles