C # ref and out key

Source: Internet
Author: User

Today, when I read a piece of C # code, I found that I don't know the ref and out keys. So I checked the C # language-related tutorials and learned them in depth.

The ref keyword is used to pass the parameter by reference type, so that when the control is passed to the call method, any changes made to the parameter in the method will be reflected in the variable.

The reference type is mentioned here. In fact, there are two types in C #, one is the value type (struct, value type, bool type, enumeration type, and can be empty type ), another type is reference (custom class, interface, Delegate, array, string type, object ). The difference between the value type and the reference type is as follows:

1. The value type directly stores its value. The variable itself contains instance data, while the reference type stores only the memory reference of instance data. Therefore, a value type variable will never affect other value type variables, and the two referenced type variables may point to the same address, thus affecting each other.

2. From the memory allocation perspective, the value type is usually allocated to the thread stack. When the scope ends, the occupied space is released independently, which is highly efficient and does not require address conversion, the reference type is usually distributed on the managed stack and controlled by GC, which requires address conversion and lower efficiency. This is one of the reasons c # needs to define two data types.

3. value types are implicitly derived from System. valueType, while System. valueType is directly derived from System. object, each value type has an implicit default constructor to initialize the default value of this type. Note that all value types are sealed, so a new value type cannot be derived. And System. valueType itself is a class type, not a value type. Because it overrides the Equals () method of the object, the value type is compared based on the Instance value instead of the reference address.

4. C #'s unified type system enables value types to be converted to objects for processing. This is often referred to as packing and unpacking. Since it is necessary to create a new object or perform forced type conversion for unpacking, the time and operation required for these operations is far greater than the value assignment operation, so it is not recommended to use it, at the same time, try to avoid the occurrence of implicit unpacking.

Note: The stack is a continuous memory area allocated by the operating system for fast data access. Because the capacity of the value type is known, it can be stored on the stack. Managed heap is a continuous memory area reserved by CLR for the application at startup, and is used for dynamic memory allocation. The reference type of capacity can only be determined at runtime, all reference types are stored in heap.

After understanding the difference between the C # value type and the reference type, it is very easy to look at the ref keyword. The following is a small example to illustrate the role of the ref keyword.

The function of the following code is to sort two integers in ascending order.

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace ref1
{
Class Program
{

/// <Summary>
/// Sort data from small to large
/// </Summary>
/// <Param name = "a"> </param>
/// <Param name = "B"> </param>
Public static void sawp (int a, int B)
{
Int c = 0;
If (a> B)
{
C =;
A = B;
B = c;
}
Console. WriteLine ("a value: {0}, B value: {1}", a, B );
}

Static void Main (string [] args)
{
Int x = 6;
Int y = 4;
Sawp (x, y );
Console. writeline ("x value: {0}, Y value: {1}", x, y );
Console. Readline ();
}
}
}

The running result is as follows:

The program runs unexpectedly. After careful analysis, we will find that the swap function parameters are passed through values, which only exchange the copy values of X and Y, the value in the memory remains unchanged. Now we add the ref keyword before the parameter.

View Code using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace ref1
{
Class Program
{

/// <Summary>
/// Sort data from small to large
/// </Summary>
/// <Param name = "A"> </param>
/// <Param name = "B"> </param>
Public static void sawp (ref int A, ref int B)
{
Int C = 0;
If (a> B)
{
C =;
A = B;
B = c;
}
}

Static void Main (string [] args)
{
Int x = 6;
Int y = 4;
Sawp (ref x, ref y );
Console. WriteLine ("x value: {0}, y value: {1}", x, y );
Console. ReadLine ();
}
}

The running result is as follows:

As you can see, the program provides the correct results.

Next, let's talk about the out keyword. The out keyword function is similar to the ref keyword function. The out keyword is used to transmit parameters through applications. The difference between them is that the key requirement of ref is that variables must be initialized before being passed, but out does not.

The following uses a small example to learn the out keyword.

View Code using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace ref1
{
Class Program
{
Static int maxindex (INT [] m_array, out int m_index)
{
M_index = 0;
Int m_max = m_array [0];
For (INT I = 0; I <m_array.length; I ++)
{
If (m_array [I]> m_max)
{
M_max = m_array [I];
M_index = I;
}
}
Return m_max;
}
Static void main (string [] ARGs)
{
Int [] Array = new int [5] {12, 22, 55, 44, 11 };
Int maxIndex; // use the out keyword. Initialization is not required here.
Console. WriteLine ("the maximum value in the Array is: {0}", MaxIndex (Array, out maxIndex ));
Console. WriteLine ("Maximum index number: {0}", maxIndex + 1 );
Console. ReadLine ();
}
}
}

The running result is as follows:

In fact, the above program can also use the ref keyword to write:

View Code using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace ref1
{
Class Program
{

/// <Summary>
/// Returns the index value of the maximum and maximum values of the array.
/// </Summary>
/// <Param name = "m_array"> array </param>
/// <Param name = "m_index"> maximum index value </param>
/// <Returns> maximum value in the array </returns>
Static int maxindex (INT [] m_array, ref int m_index)
{
M_Index = 0;
Int m_Max = m_Array [0];
For (int I = 0; I <m_Array.Length; I ++)
{
If (m_Array [I]> m_Max)
{
M_Max = m_Array [I];
M_Index = I;
}
}
Return m_Max;
}
Static void Main (string [] args)
{
Int [] Array = new int [5] {12, 22, 55, 44, 11 };
Int maxindex = 0; // use the ref keyword. Initialization is required here.
Console. writeline ("the maximum value in the array is: {0}", maxindex (array, ref maxindex ));
Console. writeline ("Maximum index number: {0}", maxindex + 1 );
Console. Readline ();
}
}
}

The running result is as follows:

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.