Reference, output and value parameters. : Ref Out « Language Basics « C# / C Sharp






Reference, output and value parameters.

 




using System;

class ReferenceAndOutputParameters
{
   public void aMethod()
   {
      int y = 5; 
      int z; 

      Console.WriteLine( "Original value of y: {0}", y );
      Console.WriteLine( "Original value of z: uninitialized\n" );

      SquareRef( ref y );  
      SquareOut( out z );  

      Console.WriteLine( "Value of y after SquareRef: {0}", y );
      Console.WriteLine( "Value of z after SquareOut: {0}\n", z );

      Square( y );
      Square( z );

      Console.WriteLine( "Value of y after Square: {0}", y );
      Console.WriteLine( "Value of z after Square: {0}", z );
   } 
   void SquareRef( ref int x )
   {
      x = x * x; 
   } 
   void SquareOut( out int x )
   {
      x = 6; 
      x = x * x; 
   } 
   void Square( int x )
   {
      x = x * x;
   }
} 
class ReferenceAndOutputParamtersTest
{
   static void Main( string[] args )
   {
      ReferenceAndOutputParameters test = new ReferenceAndOutputParameters();
      test.aMethod();
   }
}


        








Related examples in the same category

1.Testing the effects of passing array references by value and by reference.
2.the out descriptor allows a function a value in an argument without initializing the argumentthe out descriptor allows a function a value in an argument without initializing the argument
3.compare the difference between passing a null reference vs. a reference to a zero length string