Friday, 9 January 2015

C# 6 (Part 2)

String Interpolation

String interpolation is a replacement/alternative to string.format.

 var name = "Rob";  
 var output = "Hello \{name}";  
   
 Console.WriteLine(output);  

This will output "Hello Rob"

This is quite a nice feature as I find the syntax a lot easier to read than string.format.

Resharper 9.1 does not support this yet and will highlight it as an error, but it still compiles and runs.

https://roslyn.codeplex.com/discussions/540869
https://roslyn.codeplex.com/discussions/570614

nameof Operator

Quick and easy way of getting the name of something
 Console.WriteLine(nameof(test));  // varable outputs: "test"
 Console.WriteLine(nameof(TestProperty));  // property outputs: "TestProperty"
 Console.WriteLine(nameof(MyClass.TestProperty));  // property of class outputs: "TestProperty"
 Console.WriteLine(nameof(System.Text));   // namespace outputs: "Text"
 Console.WriteLine(nameof(MyClass.Method));  // method outputs: "Method"

Another useful little feature for when you are setting things using reflection and don't want to use strings, you can use an expression tree but this is simpler and I assume more efficient.

Resharper 9.1 does not support yet but it still compiles and runs
https://roslyn.codeplex.com/discussions/570551

Expression Bodied Members

You can now define fields with lambda expressions.


 private int _total => _first + _second;  
 private static Program CreateProgram => new Program();  

Can also be used to define methods.

 public int Add(int x) => _number += x;  

Nice little feature for quick definition of simple methods.

Exception Filters
It is now possible to filter exceptions without affecting the stack trace.
 try  
 {  
   ThrowException();  
 }  
 catch (Exception e) if (e is InvalidDataException || e is InvalidOperationException)  
 {  
   // Handle it  
 }  

This can also be used (abused) to log exceptions.
 try  
 {  
   ThrowException();  
 }  
 catch (Exception e) if (Log(e))  
 {  
   // Handle it  
 }  
This seems to be an acceptable abuse of the feature as it is described in the language spec :)

No comments:

Post a comment