Fix To: The Out Parameter Must Be Assigned to Before Control Leaves the Current Method

Introduction

  • The out keyword causes arguments to be passed by reference.
  • To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
  • Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Example

Simple Program to check whether the given character exists or not,

  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main ( )  
  6.     {  
  7.         bool sharpsymbol; // Used as out parameter.  
  8.         bool AndSymbol;  
  9.         bool Paranthesis;  
  10.         const string value = "& # @";// Used as input string.  
  11.   
  12.         CheckString ( value, out sharpsymbol, out AndSymbol, out Paranthesis );  
  13.   
  14.         Console.WriteLine ( value ); // Display value.  
  15.         Console.Write ( "sharpsymbol: " ); // Display labels and bools.  
  16.         Console.WriteLine ( sharpsymbol );  
  17.         Console.Write ( "AndSymbol: " );  
  18.         Console.WriteLine ( AndSymbol );  
  19.         Console.Write ( "Paranthesis: " );  
  20.         Console.WriteLine ( Paranthesis );  
  21.         Console.ReadLine ( );  
  22.     }  
  23.   
  24.     static void CheckString ( string value,  
  25.     out bool sharpsymbol,  
  26.     out bool AndSymbol,  
  27.     out bool Paranthesis )  
  28.     {  
  29.         // Assign all out parameters to false.  
  30.     
  31.   
  32.         sharpsymbol = AndSymbol = Paranthesis = false;  
  33.   
  34.         for(int i = 0; i < value.Length; i++)  
  35.         {  
  36.             switch(value[i])  
  37.             {  
  38.                 case '#':  
  39.                     {  
  40.                         sharpsymbol = true// Set out parameter.  
  41.                         break;  
  42.                     }  
  43.                 case '&':  
  44.                     {  
  45.                         AndSymbol = true// Set out parameter.  
  46.                         break;  
  47.                     }  
  48.                 case '(':  
  49.                     {  
  50.                         Paranthesis = false// Set out parameter.  
  51.                         break;  
  52.                     }  
  53.             }  
  54.         }  
  55.     }  
  56. }  
Output

Output

When the Problem Occurs.

code

Note

In the above program, even though you assigned the out variable value inside the looping/case statement, if you don't assign any value in the method definition like the above snagit then you will get the following error:

error

Conclusion

I hope the above information is useful for beginners, kindly let me know your thoughts.
Ebook Download
View all
Learn
View all