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,
- using System;
- class Program
- {
- static void Main ( )
- {
- bool sharpsymbol; // Used as out parameter.
- bool AndSymbol;
- bool Paranthesis;
- const string value = "& # @";// Used as input string.
- CheckString ( value, out sharpsymbol, out AndSymbol, out Paranthesis );
- Console.WriteLine ( value ); // Display value.
- Console.Write ( "sharpsymbol: " ); // Display labels and bools.
- Console.WriteLine ( sharpsymbol );
- Console.Write ( "AndSymbol: " );
- Console.WriteLine ( AndSymbol );
- Console.Write ( "Paranthesis: " );
- Console.WriteLine ( Paranthesis );
- Console.ReadLine ( );
- }
- static void CheckString ( string value,
- out bool sharpsymbol,
- out bool AndSymbol,
- out bool Paranthesis )
- {
- // Assign all out parameters to false.
- sharpsymbol = AndSymbol = Paranthesis = false;
- for(int i = 0; i < value.Length; i++)
- {
- switch(value[i])
- {
- case '#':
- {
- sharpsymbol = true; // Set out parameter.
- break;
- }
- case '&':
- {
- AndSymbol = true; // Set out parameter.
- break;
- }
- case '(':
- {
- Paranthesis = false; // Set out parameter.
- break;
- }
- }
- }
- }
- }
Output
When the Problem Occurs.
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:
Conclusion
I hope the above information is useful for beginners, kindly let me know your thoughts.