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# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.