Return Ref Local - CSharp Language Basics

CSharp examples for Language Basics:ref

Description

Return Ref Local

Demo Code

using System;//from   w  w w.ja v a2s .c  om
using System.ComponentModel;
using System.Diagnostics;
public class RefLocalReturnIntro
{
   static void Main()
   {
      int odd = 0;
      int even = 1;
      Stopwatch stopwatch = Stopwatch.StartNew();
      while (stopwatch.Elapsed.TotalSeconds < 5)
      {
         ref int picked = ref PickOddOrEven(ref odd, ref even);
         picked++;
      }
      Console.WriteLine($"Iterations in odd seconds: {odd}");
      Console.WriteLine($"Iterations in even seconds: {even}");
   }
   static ref int PickOddOrEven(ref int odd, ref int even)
   {
      if ((DateTime.UtcNow.Second & 1) == 1)
      {
         return ref odd;
      }
      else
      {
         return ref even;
      }
   }
}

Result


Related Tutorials