easy to understand the difference between ref and out

ref and out are two keywords in C # developers frequently used, but many people do not figure out the difference between these two specific keywords, we look for these two key differences below.

Similarities and differences zero, ref and out of

  1. the same:
  • They are passed by address;
  • After use will change the original value of the parameter;
  • Treated the same compile time;
  • Attribute can not passed as parameters.
  1. different:
  • ref parameter value passed into the Method, OUT can not be passed to the method parameter value;
  • ref before passing parameters must be initialized, OUT necessary to initialize the parameters before transmission method, but must be initialized in the process;
  • ref used in the method needs to be called a modified reference caller when, OUT used in place need to return multiple results.

First, the code shows

ref parameter value passed into the Method

static void Main(string[] args)
{
    //初始化
    int number = 50;
    Console.WriteLine("调用方法前 number 值:" + number);
    RefFunction(ref number);
    Console.WriteLine("调用方法后 number 值:" + number);
    Console.Read();
}

// 传入的参数值是 50 ,方法中使用的num值也是50
static void RefFunction(ref int num)
{
    num = num / 2;
}

The output is shown below:
Zh3gpQ.png

out can not be the parameter values passed to the method

static void Main(string[] args)
{
    int number = 50;
    Console.WriteLine("调用方法前 number 值:" + number);
    OutFunction(out number);
    Console.WriteLine("调用方法后 number 值:" + number);
    Console.Read();
}

// 无法将的参数值50传入 ,但是必须在方法中初始化
static void OutFunction(out int num)
{
    //初始化
    num = 120;
    num = num / 2;
}

The output is shown below:
Zh8EnI.png

Small expansion: If a method using ref or out parameter, and the other method does not use these two types of parameters, it can be reloaded. The example code below is overloaded can be compiled:

static void Function(out int num)
{
    num = 120;
    num = num / 2;
}
static void Function(int num)
{
    num = num / 2;
}

Guess you like

Origin www.cnblogs.com/gangzhucoll/p/11260900.html