Sponsored Ad

Thursday, October 15, 2009

C# Out

The out keyword causes arguments to be anesthetized by reference. This is agnate to the ref keyword, except that ref requires that the capricious be initialized afore getting passed. To use an out parameter, both the adjustment analogue and the calling adjustment have to absolutely use the out keyword. Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.The ref and out keywords are advised abnormally at run-time, but they are advised the aforementioned at abridge time.Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument.

class OutReturnExample
{
    static void Method(out int i, out string s1, out string s2)
    {
        i = 44;
        s1 = "I've been returned";
        s2 = null;
    }
    static void Main()
    {
        int value;
        string str1, str2;
        Method(out value, out str1, out str2);
        // value is now 44
        // str1 is now "I've been returned"
        // str2 is (still) null;
    }
}

 

Example

// cs_out.cs
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);
   }
}

 

Output

-1
b

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers