Primary Constructor
When declaring a primary constructor all other constructors must call the primary constructor using :this().class Person(string name, int age) { private string _name = name; private int _age = age; private string _address; public Person(string name, int age, string address) : this(name, age) { _address = address; } public void Speak() { Console.WriteLine("Hi, my name is {0} and I am {1} years old", _name, _age); } }
Auto-properties
class Person(string name, int age) { public string Name { get; set; } = name; public string Name1 { get; } = name; }
Dictionary initializer
When using dictionaries, sometimes you want to initialize them with values just as you can do with arrays and lists. You will see in the following code sample that these new initializers even work with instance variables.class Person(string name) { private DictionaryIt will of course also work with the auto-property initializers_data = new Dictionary {["Name"] = name }; Dictionary newWay = new Dictionary () { // Look at this! ["Afghanistan"] = "Kabul", ["Iran"] = "Tehran", ["India"] = "Delhi" }; }
class Person(string name, int age) { public DictionaryData { get; } = new Dictionary {["Name"] = name }; }
Declaration expressions
With the out keyword you would have to declare a variable for the result before calling the actual method.int age; CalculateAgeBasedOn(1987, out age);We no longer have to do that
CalculateAgeBasedOn(1987, out var age);
Using await in a catch or finally block
Consider logging for instance. You may want to write a file log when you catch an error but not hold up the caller for too long. In this scenario, it would be great to have the ability to await an asynchronous call inside the catch block. Equally when talking about the finally block, we may want to clean up some resources or do something particular inside the finally block that invokes an asynchronous API. As seen in the following code sample, this is now allowed.public async Task DownloadAsync() { try {} catch { await Task.Delay(2000); } finally { await Task.Delay(2000); } }
Filtering Exceptions with Exception Filters
try { throw new CustomException { Severity = 100 }; } catch (CustomException ex) if (ex.Severity > 50) { Console.WriteLine("*BING BING* WARNING *BING BING*"); } catch (CustomException ex) // to catch all other exceptions { Console.WriteLine("Whooops!"); }my thanks to: http://www.codeproject.com/Articles/808732/Briefly-exploring-Csharp-new-features http://www.dotnetcurry.com/showarticle.aspx?ID=1042
0 comments:
Post a Comment