save up to 40%

What are the differences between the ref and out keywords?

Are you preparing for IT certification? With practice questions, study notes, interactive quizzes, tips and technical articles, uCertify PrepKits ensure that you get a solid grasp of core technical concepts to ace your certification exam in first attempt.

What are the differences between the ref and out keywords?

Rating:

The following table describes the differences between the ref and out keywords:


The ref keyword The out keyword
The ref keyword is used to pass arguments by reference and must be explicitly initialized. The out keyword is used to pass arguments by reference and need not be explicitly initialized.
The method that has received the ref argument may or may not change the value of the ref argument. The method that has received the out argument must explicitly initialize the value of the out argument.
To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

class RefExample
{
   public static void Main()
   {
      int test=100;
      Console.Write(test);//print 100
      RefMethod(ref test);//call method
      Console.Write(test);//print 200
   }
   public void RefMethod(ref int test1)
   {
      test1+=100;
      Console.Write(tes1);//print 200
   }
}


class OutExample
{
   public static void Main()
   {
      int test;
      Console.Write(test);//garbage value
      OutMethod(out test);//call method
      Console.Write(test);//print 100
   }
   public void OutMethod(out int test1)
   {
      test1=100;
      Console.Write(test1);//print 100
   }
}


Rating:



Other articles

Click here to Article home

 
uCertify.com | Our Company | Articles | Privacy | Security | Contact Us | News and Press Release | uCertify India
MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD Cisco Certification: CCNA, CCENT, A+, Network+, Security+
Oracle Certification: OCP 9i, OCP 10g, OCA 9i, OCA 10g CIW foundation    EC-212-32    CISSP    Photoshop ACE    Adobe Flash ACE
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.