Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The usage of ref and out in C #

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the usage of ref and out in c #". In the daily operation, I believe that many people have doubts about the usage of ref and out in c #. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about the usage of ref and out in c #! Next, please follow the editor to study!

Introduction

There are two ways to pass parameters in C #: value and reference. The value is the value of the variable, and the reference is the address of the passed variable.

Ref and Out mentioned in this article are both reference passing. The focus of Ref is to pass the value to the calling method, while Out is to get the value of the calling method, similar to the value returned by a method with a return type.

You must pay attention to two points when using both, otherwise there will be errors in the compilation.

A) the ref variable should be declared and assigned a value of axi20 before using it.

B) add the corresponding keyword ref or out to the method call parameter

Application scenario

Out

Modifies function parameters to pass parameters to the function by passing a reference.

The out keyword can also be used in conjunction with a generic type parameter to specify that the type parameter is covariant.

Ref

Modifies function parameters to pass parameters to the function by passing a reference.

In the method signature, the value is returned to the caller by reference. This feature is added in c# 7.0. That is, the return value is referenced. For example:

Static ref int GetUserId (int [] allUserid) {return ref allUserid [1];}

Modifies local variables. (added to censor 7.0)

Int x = 3; ref int x1 = ref x; / / notice here that we assign x to x1 x1 = 2 through the ref keyword; Console.WriteLine ($"the changed variable {nameof (x)} value is: {x}")

The running result is 2.

Declare ref struct or ref readonly struct in the struct declaration to implement the reference semantics of the value type (added to censor 7.2, which is not discussed here)

Something in common

Both ref and out can modify the parameters of the function, indicating that the parameters are passed by reference.

The IL code generated by ref and out under the c # compiler is the same. The generated metadata is almost the same. Some online articles say that metadata is exactly the same, but it is wrong. There is actually a bit in the metadata to mark whether it is ref or out, which is just the difference of a bit. Otherwise, how do you think when the program is executed, it is ref or out?

Function parameters modified with ref or out cannot set default values. Because there is no way to pass a meaningful default value for these parameters.

If the arguments of a function are modified with ref or out, the caller of the function must pass the same parameter type as the function defines (not even inheritance). The following code is compiled and fails

Static void Main (string [] args) {MyClass c = new MyClass (); / / the following statement compiles the error Testref (out c); Console.Read ();} static void Testref (out object C1) {C1 = new object ();} class MyClass {public int Id {get; set;}}

Differences

There is a bit difference in compiled metadata, which has been mentioned above, but not too much here.

For method overloading, the c # compiler does not allow only the difference between ref and out overloaded methods. The overloaded form of the following methods is not allowed.

Void test (ref int) {} void test (out int) {}

Ref and out have different intentions for the c # compiler. Ref tells the compiler that it must be initialized before calling the function; out, on the other hand, does not have to initialize before calling the function. This actually confirms that there is some truth in the saying that "ref is used for input and out is used for output", but it is not entirely true. Can't I ref be used for the output of methods? Ha ha ha

Class Program {static void Main (string [] args) {int I = 10; Console.WriteLine (I); Test (ref I); Test (ref I); Console.WriteLine (I); Console.Read ();} static void Test (ref int i) {I + = 10;}}

Running result:

ten

thirty

So I think the real usage is:

Ref is in and out, while out is just not in and out.

Out-decorated function variables are write-only (not readable) before initialization in the called method, and must be initialized before the function finishes execution. The following method compilation reported an error because the out parameter was not initialized

Static void Testref (out MyClass C1) {}

Ref is writable and readable.

Performance

In fact, after understanding the basic principles and functions of ref and out, how to use it to improve performance is already very clear. If the value type parameter is relatively large and the business does not need to copy and modify, of course, it is more reasonable to use reference. As for the scenario where there are no special requirements for reference types, I don't think it is necessary to add ref or out to add icing on the cake.

Other

Ref and out decorate reference type parameters

Some students will ask, isn't it true that reference type parameters are already passed by reference? is there any point in adding ref or out tags? Indeed, in most cases, there is no need to add ref or out to the passing of reference type parameters, but if I change the memory address of the pointer in the method body, our method caller needs this new memory address? For example, the following is a requirement for reading N files continuously:

Static void Main (string [] args) {FileStream fs = new FileStream ("new file address", FileMode.Open); / / the operation of the first file is omitted / / and then read N file contents bool isHaveFile = true; for (; fsroomnull; ReadFile (ref fs, isHaveFile)) {fs.Read (.) / / add to determine whether there are still files to read / / isHaveFile= false;} Console.Read ();} static void ReadFile (ref FileStream fs,bool isHaveFile=true) {fs.Close (); if (! isHaveFile) fs = null; else {fs = new FileStream ("new file address", FileMode.Open);}}

It can be seen that the addition of ref or out to the reference type is necessary in some specific scenarios.

At this point, the study of "the use of ref and out in c #" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report