search
HomeBackend DevelopmentC#.Net TutorialDetailed introduction to the difference between out and ref in C# (picture and text)

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;
 }

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;
}

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;
 }

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;}

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;
 }

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
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
C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.