The same and difference between ref and out in C#
The out and ref keywords are sometimes used in the process of writing a program; because they are somewhat similar, they often give people some illusions. To use them correctly, a clear understanding of their differences is essential.
The same and difference between ref and out in C#
1. out and ref have the same point: they are all passed by address, and the original value is changed after the method is executed.
2. Difference between ref and out in C#:
1) When using ref, the passed-in arguments must be initialized; when using out, there is no need to initialize.
2) ref can pass the value of argument into the method; while out must clear the argument(even if the argument has been assigned), when exiting the method, all arguments of out must be assigned.
Specific examples are as follows:
using System;
class RefOutTest
{
static void refTest(ref int a, ref int b)
{
a = 10;
b = a;
}
static void outTest(out int a, out int b)
{
//Before leaving this method, you must assign values to a and b, otherwise an error will be reported.
a = 10;
b = 20;
}
static void Main()
{
int a = 1, b = 2;
refTest(out a, out b);
Console.WriteLine("a = {0}, b = {1}", a, b);
int x,y;
outTest(out x, out y);
Console.WriteLine("x = {0}, y = {1}", x, y);
}
}
Program execution output:
a = 10, b = 10
x = 10, y = 20
-
Related Reading
- C# listview select row(a row and multiple rows)
- Solve the flickering problem of C# listview multithr
- C# convert punctuation marks to Unicode encoding
- C# Read and write to text file Newline, with one lin
- C# merge binary array(byte array)
- C# hashtable synchronized and SyncRoot(cost comparis
- C# gridview checkbox cannot get value(reason and sol
- C# Winform button transparent background with proper
- No-refresh AjaxPro easy to ignore vulnerabilities in
- Error cs1010 newline in constant - .net(C#) mislabel
- Convert Unicode to string C#(with string to unicode)
- C# Why does the generated random number repeat and g