Home >Backend Development >C#.Net Tutorial >Detailed explanation of the three keywords in C# (params, Ref, out)

Detailed explanation of the three keywords in C# (params, Ref, out)

黄舟
黄舟Original
2017-05-21 10:47:011577browse

This article mainly discusses the params keyword, ref keyword, and out keyword. Very good, has reference value, friends who need it can refer to it

Before you can study some of the original operations about these three keywords

using System;
using System.Collections.Generic;
using System.Text;
namespace ParamsRefOut
{
  class Program
  {
    static void ChangeValue(int i)
    {
      i=5;
      Console.WriteLine("The ChangeValue method changed the value "+i.ToString());
    }
    static void Main(string[] args)
    {
      int i = 10;
      Console.WriteLine("The value of I is "+i.ToString());
      ChangeValue(i);
      Console.WriteLine("The value of I is " + i.ToString());
      Console.ReadLine();
    }
  }
}

observe the running results and find out

The value has not been changed, which means that the principle of the operation at this time may be the same as the previous function operation of C language

This article mainly discusses the params keyword, ref keyword, and out keyword.

 1) The params keyword, the official explanation is that it is used when the method parameter length is variable. Sometimes you are not sure how many method parameters a method has. You can use the params keyword to solve the problem.

using System;
using System.Collections.Generic;
using System.Text;
namespace ParamsRefOut
{
  class number
  {
    public static void UseParams(params int [] list)
    {
      for(int i=0;i<list.Length;i++)
      {
        Console.WriteLine(list[i]);
      }
    }
    static void Main(string[] args)
    {
      UseParams(1,2,3);
      int[] myArray = new int[3] {10,11,12};
      UseParams(myArray);
      Console.ReadLine();
    }
  }
}

 2) ref keyword: Use to reference the type parameter. Any changes made to the parameter in the method will be reflected in the variable

using System;
using System.Collections.Generic;
using System.Text;
namespace ParamsRefOut
{
  class number
  {
    static void Main()
    {
      int val = 0;
      Method(ref val);
      Console.WriteLine(val.ToString());
    }
    static void Method(ref int i)
    {
      i = 44;
    }
  }
}

 3) out keyword: out is similar to ref but out does not need to be initialized.

The above is the detailed content of Detailed explanation of the three keywords in C# (params, Ref, out). 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