New C sharp 7 features in action: out variables to make using out parameters smooth

Before C# 7, for calling a method with out parameters, we were required to declare variables to pass to it. Now with C# 7 out parameters enhancements (out variables):

  1. we can declare a variable right at the point where it is passed as an out argument
  2. we can use var instead of a type to declare out variables
  3. we can ignore out parameters that are not required

Below are some examples to explains the use of C# 7’s out variables (out parameters enhancements):

Before C# 7: Sample code to explain the use of out parameters in older versions of C#

Modifications to the above sample code to use C# 7’s out variables (out parameters enhancements):

  • Inside IsValidInputStringWithErrorLogging  method, we have declared errorMessage variable right at the point where it is passed as an out argument to HasValue method.
  • Inside IsValidInputStringWithErrorLogging  method, var is used instead of a type to declare out errorMessage  variable.
  • Inside IsValidInputStringWithoutErrorLogging method, we don’t require out parameter (errorMessage) value from HasValue method, so we have ignored the out parameter.

Note the highlighted changes in the below code.

Few more examples:

Before C# 7: Some custom String Extensions sample code (note the use of out parameters) in older versions of C#

Modifications to String Extensions sample code to use C# 7’s out variables (out parameters enhancements):

Note the highlighted changes in the below code.

Happy Coding !!!

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone's Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *