{"id":1786,"date":"2016-02-17T09:00:38","date_gmt":"2016-02-17T08:00:38","guid":{"rendered":"https:\/\/sii.pl\/blog\/?p=1786"},"modified":"2023-10-05T17:17:51","modified_gmt":"2023-10-05T15:17:51","slug":"c-6-features","status":"publish","type":"post","link":"https:\/\/sii.pl\/blog\/en\/c-6-features\/","title":{"rendered":"C# 6 features"},"content":{"rendered":"\n<p>Changes presented in C# 6.0 are not particularly exceptional, however, the main goal in this version was to simplify your code, so most of the new features are intended to provide more intuitive syntax.<\/p>\n\n\n\n<p>All new features of C# 6 require the C# 6.0 compiler but it\u2019s important to notice that all of them don\u2019t require any specific version .NET Framework \u2013 because all features are implemented in the compiler and don\u2019t depend on .NET Framework.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Auto-property initializers<\/h2>\n\n\n\n<p>Prior to C# 6 for initializing immutable properties we had to use private readonly fields. This solution ensures proper access to those properties but with many properties there is lot of irrelevant code lines. The other way was to create properties with private setter however it makes properties mutable for methods within the class. C# 6 introduce new feature to solve that issue in a simple way \u2013 we can declare a property with only getter and initialize it in the constructor.<br>Furthermore C# 6 allows to initialize properties directly within their declaration, the same way as fields. Initializers can be any expression (but not using this).<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class A\n{\npublic string X { get; } = \"valueOfX\";\npublic DateTime StartDay { get; } = DateTime.Today;\n}\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Null-Conditional Operator<\/h2>\n\n\n\n<p>Every .NET developer knows the NullReferenceException which is usually result of not sufficient null checking before invoking a member on that object. Let\u2019s consider this example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nif (personList != null)\n{\nPerson first = personList&#x5B;0];\nint count = personList.Count;\n}\n<\/pre><\/div>\n\n\n<p>The null checking is required, otherwise the NullReferenceException would be thrown. C# 6 allows to write it much more simple with new feature.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nPerson first = personList?&#x5B;0];  \/\/ null if customers is null\nint? nullableCount = personList?.Count; \/\/ null if customers is null\nint count = personList?.Count ?? 0; \/\/ 0 if customers is null\n<\/pre><\/div>\n\n\n<p>The null-conditional operator returns null for null-value.<br>But what happens when the null-conditional operator appears within a call chain? Consider the example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nvar dob = person?.DateOfBirth?.ToString();\n<\/pre><\/div>\n\n\n<p>It seems that since person?.DateOfBirth? just returns null there should be a NullReferenceException thrown, but this situation is handled with the language behavior that returns null immediately, without attempting execution further instruction, with no exceptions. This is a concept known as null-propagation.<br>What about a data type for the result of null-conditional? For example a data type for someValue?.Length \u2013 we can\u2019t use int. Attempting to assign it to int will results with compile error. In that case really handy are nullable types.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nint? length = person?.Name?.Length;\n<\/pre><\/div>\n\n\n<p>But we can also use the null-coallescing operator at the end of expression:<br>var count = post?.Tags?.Count ?? 0;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nint length = person?.Name?.Length ?? 0;\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Expression Bodied Methods and Auto-Properties<\/h2>\n\n\n\n<p>Expression bodied functions and auto-properties are implemented with an expression following the function declaration instead of statement body. To assign the expression use the arrow operator (=&gt;). This simplified implementation can be used for methods with or without parameters. The same way we can implement read-only (getter only) properties \u2013 called expression bodied properties.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic TimeSpan Age =&gt; DateTime.Now \u2013 DateOfBirth;\npublic override string ToString() =&gt; string.Format(&quot;{0} is {1} old.&quot;, Name, Age);\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Dictionary initializers<\/h2>\n\n\n\n<p>Prior to C# 6.0 the common method for initializing and filling Dictionary includes the {key, value} syntax. This is easy to implement for simple objects but when we have more complex object with nested structures might be not very clear and it\u2019s easy to lose track of all those curly brackets.<br>In C# 6 there is an improvement of dictionary assignment, using index-based syntax. The data types of key-value pairs are corresponding to the types declared for the dictionary.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nvar peopleDict = new Dictionary&lt;string, Person&gt;;\n{\n&#x5B;&quot;mike&quot;] = new Person(&quot;Mike Smith&quot;, 28),\n&#x5B;&quot;lilly&quot;] = new Person(&quot;Lilly Potter&quot;, 25)\n};\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">String Interpolation<\/h2>\n\n\n\n<p>To display strings combined in one composite string we used string.Format() method. Probably any .NET developer struggled with that when there are many strings to put together. This is not easy to read or validate. The placeholders and parameters must be in proper order.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nstring.Format(\"{0} {1} was born {2} and now is {3}.\", FirstName, LastName, DateOfBirth, Age);\n<\/pre><\/div>\n\n\n<p>In C# 6 there is new alternative approach to composite formatting. The result of string.Format() we can obtain using string literal prefixed with a \u201c$\u201d and each argument within curly brackets.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n$\"{FirstName} {LastName} was born {DateOfBirth} and now is {Age}.\";\n<\/pre><\/div>\n\n\n<p>The string interpolation syntax prevent from disordered or missing arguments errors. Compiler transforms it into string.Format() so in effect there are no changes (eg. Localization). That means also that we can use options from original method defining format of an argument or use an expression.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nstring s = $\"It is now {DateTime.Now:d} at {DateTime.Now:t}\";\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\"><strong>Using static<\/strong><\/h2>\n\n\n\n<p>Another feature simplifying C# code is using static. Prior to C# 6 there was possible to use only namespaces in the using directive but with this feature you can use type of static class. Therefore you can gain access to static members of type without prefix of the type name \u2013 you can invoke them directly.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n\/\/prior to C# 6\nvar result = Math.Sqrt(Math.Abs(x) * Math.Pow(y, 2) + z * Math.PI);\n\/\/C# 6\nvar result = Sqrt(Abs(x) * Pow(y, 2) + z * PI);\n<\/pre><\/div>\n\n\n<p>With using static you can restrict access to extension methods to single class unlike using namespace \u2013 when all of extension methods from this namespace are available.<br>Enums can also be called that way. It is very useful if the names of enum items are understandable and clear without type prefix.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing static System.ConsoleKey;\n\/\/\u2026\nswitch (keypressed)\n{\ncase A:\nbreak;\ncase B:\nbreak;\n}\n<\/pre><\/div>\n\n\n<p>What about aliases to namespace? For example char \u2013 to use this type it\u2019s required to write full namespace, in this case System.Char.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing static char; \/\/Error\nusing static System.Char; \/\/Correct\n<\/pre><\/div>\n\n\n<p>Be careful with using static though \u2013 in situation when you specify using static for types that have a member with the same name \u2013 to distinguish them it\u2019s required to add prefix of the type name while invoking them.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing static System.IO.Directory;\nusing static System.IO.File;\n\/\/\u2026\nif (!Exists(filename)) \/\/ ERROR: The call is ambiguous between the following methods or properties: 'Directory.Exists(string)' and 'File.Exists(string)'\n{\nthrow new ArgumentException(\"The file does not exist.\", nameof(filename));\n}\n<\/pre><\/div>\n\n\n<p>This feature was added to simplifying your code and make it more readable, but when the context is not obvious and using static could lead to confusion you probably shouldn\u2019t use it. It\u2019s best to limit number of the using static directives to just a few classes which you use frequently.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>The nameof Operator<\/strong><\/h2>\n\n\n\n<p>As the name of this feature suggests \u2013 operator nameof returns the name of any item like class, method, property or parameter. When the fully qualified identifier is passed as parameter to nameof() it will return just the final identifier (last part). This feature protects from runtime errors caused by misspellings and also works with renaming tools. nameof(someFancyParameterName) will return someFancyParameterName.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Exception Improvements<\/strong><\/h2>\n\n\n\n<p>Prior to C# 6 the exception filtering was only possible on the type level but now there was introduced the \u201cwhen\u201d clause to do more accurate filtering for exceptions. After a catch() you can now add an extra condition.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\ntry\n{\nthrow new Exception(\"My exception\");\n}\ncatch (Exception ex) when (ex.Message == \"My exception\")\n{\nConsole.WriteLine(\"My exception caught\");\n}\ncatch (Exception ex)\n{\nConsole.WriteLine(\"Other exception caught here\");\n}\n<\/pre><\/div>\n\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-bottom\"\n    data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1786&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;bottom&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;4&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;4.7&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;11&quot;,&quot;greet&quot;:&quot;&quot;,&quot;legend&quot;:&quot;4.7\\\/5 ( votes: 4)&quot;,&quot;size&quot;:&quot;18&quot;,&quot;title&quot;:&quot;C# 6 features&quot;,&quot;width&quot;:&quot;130.8&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} ( {votes}: {count})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n            \n<div class=\"kksr-stars\">\n    \n<div class=\"kksr-stars-inactive\">\n            <div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n    <\/div>\n    \n<div class=\"kksr-stars-active\" style=\"width: 130.8px;\">\n            <div class=\"kksr-star\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n            <div class=\"kksr-star\" style=\"padding-right: 11px\">\n            \n\n<div class=\"kksr-icon\" style=\"width: 18px; height: 18px;\"><\/div>\n        <\/div>\n    <\/div>\n<\/div>\n                \n\n<div class=\"kksr-legend\" style=\"font-size: 14.4px;\">\n            4.7\/5 ( votes: 4)    <\/div>\n    <\/div>\n","protected":false},"excerpt":{"rendered":"<p>Changes presented in C# 6.0 are not particularly exceptional, however, the main goal in this version was to simplify your &hellip; <a class=\"continued-btn\" href=\"https:\/\/sii.pl\/blog\/en\/c-6-features\/\">Continued<\/a><\/p>\n","protected":false},"author":80,"featured_media":15202,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_editorskit_title_hidden":false,"_editorskit_reading_time":0,"_editorskit_is_block_options_detached":false,"_editorskit_block_options_position":"{}","inline_featured_image":false,"footnotes":""},"categories":[1320],"tags":[1425,1486],"class_list":["post-1786","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-hard-development","tag-c-en","tag-c-6-0-en"],"acf":[],"aioseo_notices":[],"republish_history":[],"featured_media_url":"https:\/\/sii.pl\/blog\/wp-content\/uploads\/2016\/02\/BlogersiiCovery-sd.jpg","category_names":["Hard development"],"_links":{"self":[{"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/posts\/1786"}],"collection":[{"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/users\/80"}],"replies":[{"embeddable":true,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/comments?post=1786"}],"version-history":[{"count":2,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/posts\/1786\/revisions"}],"predecessor-version":[{"id":24848,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/posts\/1786\/revisions\/24848"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/media\/15202"}],"wp:attachment":[{"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/media?parent=1786"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/categories?post=1786"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sii.pl\/blog\/en\/wp-json\/wp\/v2\/tags?post=1786"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}