{"id":32696,"date":"2017-08-02T12:06:36","date_gmt":"2017-08-02T19:06:36","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=32696"},"modified":"2019-03-25T19:26:59","modified_gmt":"2019-03-26T03:26:59","slug":"getting-started-c-7","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/getting-started-c-7\/","title":{"rendered":"Getting Started with C# 7"},"content":{"rendered":"<p>\t\t\t\tThe releases of Visual Studio 2017 and Visual Studio for Mac introduced two spectacular new IDEs to develop mobile applications, cloud workloads, and introduced us to a world of powerful new C# features with the release of C# 7. I recently <a href=\"http:\/\/motzcod.es\/post\/161630386432\/my-favorite-c-7-feature-more-expression-bodied\" target=\"_blank\">blogged about my favorite new feature<\/a>, expression bodied members, and even <a href=\"http:\/\/www.mergeconflict.fm\/merge-conflict-47-you-got-some-fsharp-in-my-csharp\" target=\"_blank\">recorded an entire podcast<\/a> about how awesome C# 7 is. In this blog post, I&#8217;ll show you how to get started with C# 7 and some features that you can take advantage of right away in your mobile apps.<\/p>\n<h2>Tuples!<\/h2>\n<p>When you want to return multiple values from a function, Tuples are the way to go. C# 7 provides rich syntax and functionality that make Tuples a first class citizen with the introduction of the <a href=\"https:\/\/www.nuget.org\/packages\/System.ValueTuple\/\" target=\"_blank\">System.ValueTuple NuGet package<\/a>. After installing the NuGet, we&#8217;re ready to start using Tuples as lightweight data structures with full IntelliSense.<\/p>\n<h3>Tuple Declaration<\/h3>\n<p>We can now create Tuples in several ways:<\/p>\n<pre class=\"lang:c# decode:true\">var names = (\"James\", \"Montemagno\");<\/pre>\n<p>As you can see, this automatically creates a Tuple with members of <em>Item1<\/em> and <em>Item2<\/em>, but we can do better!<\/p>\n<pre class=\"lang:c# decode:true\">(string First, string Last) names = (\"James\", \"Montemagno\");<\/pre>\n<p>Or&#8230;<\/p>\n<pre class=\"lang:c# decode:true\">var names = (First: \"James\", Last: \"Montemagno\");\r\n\r\n\/\/ accessed with:\r\nvar first = names.First;<\/pre>\n<h3>Returning Tuples<\/h3>\n<p>Now that we know how to declare tuples, we can use them in a method:<\/p>\n<pre class=\"lang:c# decode:true \">static (string First, string Last) GetName(int index)\r\n{\r\n   var first = string.Empty;\r\n   var last = string.Empty;\r\n\r\n   \/\/ Go to database and get names\r\n   var person = GetPersonFromDatabase(index);\r\n   first = person.FirstName;\r\n   last = person.LastName;\r\n\r\n   return (first, last);\r\n}<\/pre>\n<p>Then we can simply call the method:<\/p>\n<pre class=\"lang:c# decode:true\">var name = GetName(1);\r\nConsole.WriteLine($\"My name is {name.First} {name.Last}.\")<\/pre>\n<p>Or&#8230;<\/p>\n<pre class=\"lang:c# decode:true\">(string first, string last) = GetName(1);\r\nConsole.WriteLine($\"My name is {first} {last}.\")<\/pre>\n<p>You can also use full async\/await support with Tasks!<\/p>\n<pre class=\"lang:c# decode:true\">static async Task GetName(int index)\r\n{\r\n   var first = string.Empty;\r\n   var last = string.Empty;\r\n\r\n   \/\/ Go to database and get names\r\n   var person = await GetPersonFromDatabaseAsync(index);\r\n   first = person.FirstName;\r\n   last = person.LastName;\r\n\r\n   return (first, last);\r\n}<\/pre>\n<h2>More Expression-Bodied Members<\/h2>\n<p>I can&#8217;t talk about C# 7 without mentioning my favorite feature, expression-bodied members, which were introduced in C# 6 and greatly enhanced in C# 7. Here&#8217;s how they improved our code in C# 6, using our good friend OnPropertyChanged as an example.<\/p>\n<pre class=\"lang:c# decode:true\">public void OnPropertyChanged(string name)\r\n{\r\n  var changed = PropertyChanged;\r\n  if(changed == null)\r\n    return;\r\n\r\n  changed(this, new PropertyChangedEventArgs(name));\r\n}<\/pre>\n<p>Now, with expression-bodied members we can write this:<\/p>\n<pre class=\"lang:c# decode:true\">public void OnPropertyChanged(string name)=&gt;\r\n  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));<\/pre>\n<p>Amazing! However, in <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/whats-new\/csharp-7#more-expression-bodied-members\" target=\"_blank\">C# 7 things get even better<\/a>. Take a look at the standard get and set accessors that I use all the time:<\/p>\n<pre class=\"lang:c# decode:true\">public string Subtitle\r\n{\r\n  get { return subtitle; }\r\n  set { SetProperty(ref subtitle, value); }\r\n}<\/pre>\n<p>Look at all of those { and }, well no more! Here is some C# 7 for you:<\/p>\n<pre class=\"lang:c# decode:true\">public string Subtitle\r\n{\r\n    get =&gt; subtitle;\r\n    set =&gt; SetProperty(ref subtitle, value);\r\n}<\/pre>\n<p>They can now also be applied to constructors, finalizers, and indexers!<\/p>\n<pre class=\"lang:c# decode:true\">public ExpressionMembers(string label) =&gt; this.Label = label;<\/pre>\n<h2>Pattern Matching<\/h2>\n<p>I love expression-bodied members, but I have to admit Pattern Matching is an absolutely delightful feature when using <code>switch<\/code> and <code>is<\/code> expressions. At its core, it enables us to inspect an object and determine if it satisfies a specific pattern that we&#8217;re expecting.<\/p>\n<p>The most simple example is when you receive an <code>Object<\/code> type and need to figure out what it is. Let&#8217;s say we have a base class of <code>Animal<\/code> with several derived classes from it for specific animal types:<\/p>\n<pre class=\"lang:c# decode:true\">bool LikesBananas(object item)\r\n{\r\n   var monkey = item as Monkey;\r\n   if(monkey != null)\r\n      return monkey.LikesBananas;\r\n\r\n   \/\/ or perhaps this way:\r\n   if(item is Animal)\r\n   {\r\n      var animal = (Animal)item;\r\n      return animal.FavoriteFood == \"Banana\";\r\n   }\r\n\r\n   return false;\r\n}<\/code><\/pre>\n<p>Now, we can simplify this by combining pattern matching and the <em>code<\/em> expression and casting the item in line:<\/p>\n<pre class=\"lang:c# decode:true\">bool LikesBananas(object item)\r\n{\r\n   if(item is Monkey monkey)\r\n      return monkey.LikesBananas;\r\n\r\n   if(item is Animal animal)\r\n     return animal.FavoriteFood == \"Banana\";\r\n\r\n   return false;\r\n}<\/pre>\n<p>Pattern Matching doesn&#8217;t stop there, as we can use it in <code>switch<\/code> cases as well:<\/p>\n<pre class=\"lang:c# decode:true\">int TotalAnimalsThatLikeBananas(IEnumberable values)\r\n{\r\n   int count = 0;\r\n   foreach(var item in values)\r\n   {\r\n      switch(item)\r\n      {\r\n         case Monkey monkey:\r\n            count += (monkey.LikesBananas ? 1 : 0);\r\n            break;\r\n         case IEnumberable subList:\r\n            count += TotalAnimalsThatLikeBanans(subList);\r\n            break;\r\n         case Animal animal:\r\n            count += (animal.FavoriteFood == \"Banana\" ? 1 : 0);\r\n            break;\r\n         case null:\r\n            \/\/ maybe throw an exception?\r\n            break;\r\n         case default:\r\n            break;\r\n      }\r\n   }\r\n   return count;\r\n}<\/pre>\n<h2>Awesome out variables<\/h2>\n<p>This one is pretty straight-forward, but also extremely powerful. When using a method that has an <code>out<\/code> variable, you always have to declare it ahead of time, as such:<\/p>\n<pre class=\"lang:c# decode:true\">int result = 0;\r\nif (!int.TryParse(input, out result))\r\n{\r\n    return null;\r\n}\r\n\r\nreturn result;<\/pre>\n<p>Not anymore! Now we can simply declare the variable inline and use it anywhere!<\/p>\n<pre class=\"lang:c# decode:true\">if (!int.TryParse(input, out int result))\r\n{\r\n    \/\/ result can be accessed here if we needed to\r\n    return null;\r\n}\r\n\r\nreturn result;<\/pre>\n<h2>Learn More<\/h2>\n<p>These are just a few of the new features that can be found in C# 7, which you can start using today in Visual Studio 2017 and Visual Studio for Mac. Be sure to read through the entire <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/whats-new\/csharp-7\" target=\"_blank\">C# 7 documentation<\/a> to learn more about all of the other exciting new features available to you right now.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The releases of Visual Studio 2017 and Visual Studio for Mac introduced two spectacular new IDEs to develop mobile applications, cloud workloads, and introduced us to a world of powerful new C# features with the release of C# 7. I recently <a href=\"http:\/\/motzcod.es\/post\/161630386432\/my-favorite-c-7-feature-more-expression-bodied\" target=\"_blank\">blogged about my favorite new feature<\/a>, expression bodied members, and even <a href=\"http:\/\/www.mergeconflict.fm\/merge-conflict-47-you-got-some-fsharp-in-my-csharp\" target=\"_blank\">recorded an entire podcast<\/a> about how awesome C# 7 is. In this blog post, I&#8217;ll show you how to get started with C# 7 and some features that you can take advantage of right away in your mobile apps.<\/p>\n","protected":false},"author":544,"featured_media":41028,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2,291],"tags":[606,4],"class_list":["post-32696","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","category-xamarin-platform","tag-c","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>The releases of Visual Studio 2017 and Visual Studio for Mac introduced two spectacular new IDEs to develop mobile applications, cloud workloads, and introduced us to a world of powerful new C# features with the release of C# 7. I recently <a href=\"http:\/\/motzcod.es\/post\/161630386432\/my-favorite-c-7-feature-more-expression-bodied\" target=\"_blank\">blogged about my favorite new feature<\/a>, expression bodied members, and even <a href=\"http:\/\/www.mergeconflict.fm\/merge-conflict-47-you-got-some-fsharp-in-my-csharp\" target=\"_blank\">recorded an entire podcast<\/a> about how awesome C# 7 is. In this blog post, I&#8217;ll show you how to get started with C# 7 and some features that you can take advantage of right away in your mobile apps.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/32696","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/544"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=32696"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/32696\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/41028"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=32696"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=32696"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=32696"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}