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;
- bool AndSymbol;
- bool Paranthesis;
- const string value = "& # @";
-
- CheckString ( value, out sharpsymbol, out AndSymbol, out Paranthesis );
-
- Console.WriteLine ( value );
- Console.Write ( "sharpsymbol: " );
- 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 )
- {
-
-
-
- sharpsymbol = AndSymbol = Paranthesis = false;
-
- for(int i = 0; i < value.Length; i++)
- {
- switch(value[i])
- {
- case '#':
- {
- sharpsymbol = true;
- break;
- }
- case '&':
- {
- AndSymbol = true;
- break;
- }
- case '(':
- {
- Paranthesis = false;
- 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.