Thursday, 8 January 2015

C# 6

Been digging in to some of the new C#6 features, a few examples/thoughts

Auto Property Initializers

Auto property initializers allow you to set the initial value without having  to do it in a constructor

 public string TestString { get; set; } = "Hello";  

This can also be used for get only properties

 public string TestString { get; } = "Hello";  

Seems like a non-static field cannot access a method to set the value:
 Cannot access non-static method 'GetString' in static context  

When changing the method to static it appears to work, interesting...
 public string TestMethodReturn { get; } = GetString();  
   
 public static string GetString()  
 {  
   return "Method";  
 }  

This appears to be because the property initializers are called before the constructor.

Think I will be using this stuff, especially setting the get only property. Nice little bits of syntactic sugar.

Constructor Assignment to get only Auto Properties

Does what it says on the tin,
 public string TestString { get; }  
 public Program()  
 {  
   TestString = "Hello";  
 }  

Also seems reasonably useful, though not sure if I will favour this or setting it on the property.

Static Using

Pretty simple, just imports the static methods for use without their class name.
 using System.Console;  
   
 WriteLine("Hello");  

Not sure if using this stuff will be a good idea as it may reduce readability, but then maybe there will be cases where this would be useful. Advise using with caution.

Dictionary Initializers

There is a new dictionary initialzer format, the old one like the following still works
 var dictionaryOld = new Dictionary<string, string>  
 {  
   {"first", "First"},  
   {"Second", "Second"},  
   {"Third", "Third"},  
 };  

The new format is as follows
 var dictionaryNew = new Dictionary<string, string>  
 {  
   ["First"] = "First",  
   ["Second"] = "Second",  
   ["Third"] = "Third",  
 };  

So why the new format, well the only reason that I can see is this allows you to use the new format initializer just by implementing a this property on your own class:
 public class MyCollection  
 {  
   private readonly Dictionary<string, string> _store = new Dictionary<string, string>();  
   
   public string this[string key]  
   {  
     get { return ""; }  
     set { _store[key] = value; }  
   }  
 }  

You can then use the new initializer when creating instances
 var custom = new MyCollection  
 {  
   ["First"] = "First",  
   ["Second"] = "Second",  
   ["Third"] = "Third",  
 };  

Think this stuff will be useful for people making custom collections, good to know it exists so that I can use it when necessary. Though i'm now not sure which initializer I should be using when initializing dictionaries...

No comments:

Post a comment