what is use of out parameter in c#

后端 未结 9 1180
南方客
南方客 2021-02-07 16:27

Can you please tell me what is the exact use of out parameter?

Related Question:
What is the differen

9条回答
  •  长发绾君心
    2021-02-07 16:41

    The out method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.

    Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter.

    To use an out parameter, the argument must explicitly be passed to the method as an out argument. The value of an out argument will not be passed to the out parameter.

    A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.

    An Example:

    using System;
    public class MyClass 
    {
       public static int TestOut(out char i) 
       {
          i = 'b';
          return -1;
       }
    
       public static void Main() 
       {
          char i;   // variable need not be initialized
          Console.WriteLine(TestOut(out i));
          Console.WriteLine(i);
       }
    }
    

提交回复
热议问题