I am here to continue the series related to C# 7.0 features. Today, we will be going through some of the enhancements introduced in out, exception and literals and will demonstrate their uses in an easy manner.
Let’s go to them one by one.
Enhancement in out parameter
Remember when using out parameter, its constraint of having it declared beforehand? The good news in C# 7.0 is that it’s no longer needed to be declared first and instead it can be declared in-line.
The snippet given below presents C# 6 and C# 7 versions.
- //In C# 6.0
- string empName;
- Console.WriteLine($"Using C#6 {CSharpSixOutTest("101", out empName)}");
- //In C# 7.0
- Console.WriteLine($"\nUsing C#7 {CSharpSevenOutTest("101", out string empName2)}");
- public static string CSharpSixOutTest(string empId, out string empName)
- {
- //Fetch empName by passing empId
- empName = "Hello Prakash!";
- return empName;
- }
Output

As you can see that in C# 7.0, it’s no longer required to have declaration of out variable beforehand.
There is one more scenario (TryParse), where out is used often and having the declaration beforehand was the constraint; butnow this has been removed in C# 7.0.
Let’s look at the example for the same in both the versions.
- CSharpOutTest("101");
- public static void CSharpOutTest(string empId)
- {
- //Using C# 6.0
- int result;
- if (int.TryParse(empId, out result))
- {
- Console.WriteLine("Parsed successfully using C#6 syntax");
- }
- //Using C# 7.0
- if (int.TryParse(empId, out int result2))
- {
- Console.WriteLine("Parsed successfully using C#7 syntax");
- }
- }
Output

As you can see in the code given above, C# 7.0 directly accepts the in-line declaration.
Enhancement in exception:
Can you throw an exception from practically everywhere?
Yes, you read it right. With C# 7.0, you can throw the exceptions from almost everywhere.
Let’s look at the example given below.
- //Exception improvements -we can throw an exception directly through expression
- Console.WriteLine(GetFirstName("Prakash Tripathi"));
- public static string GetFirstName(string name)
- {
- string[] arr = name.Split(' ');
- return (arr.Length > 0) ? arr[0] : throw new Exception("Name doesn't exist!");
- }





Sanjay GuptaPosted Apr 10, 2017, 7:16 AM
Good read Tripathi ji. Keep it up.