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