Home >Backend Development >C#.Net Tutorial >A detailed introduction to the three keywords params, Ref, and out in C#

A detailed introduction to the three keywords params, Ref, and out in C#

黄舟
黄舟Original
2017-05-28 10:09:201771browse

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 A detailed introduction to the three keywords params, Ref, and out in C#. 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