{"id":43180,"date":"2022-11-08T08:58:30","date_gmt":"2022-11-08T15:58:30","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/dotnet\/?p=43180"},"modified":"2022-11-08T09:09:33","modified_gmt":"2022-11-08T16:09:33","slug":"welcome-to-csharp-11","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/welcome-to-csharp-11\/","title":{"rendered":"Welcome to C# 11"},"content":{"rendered":"<p>I am excited to announce that C# 11 is out! As always, C# opens some entirely new fronts, even while advancing several themes that have been in motion over past releases. There are many features and many details, which are beautifully covered under <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/whats-new\/csharp-11\">What&#8217;s new in C# 11<\/a> on our docs pages. What follows here is an appetizer of some of the highlights &#8211; small and big.<\/p>\n<p>Before we dive in, let me just say how happy I am about the way this version of C# came into being! With every release there&#8217;s more and more participation from the community, contributing everything from suggestions, insights and bug reports all the way up to entire feature implementations. This is really everyone&#8217;s C#. <strong>Thank you!<\/strong><\/p>\n<h2>UTF-8 string literals<\/h2>\n<p>By default C# strings are hardcoded to UTF-16, whereas the prevailing string encoding on the internet is UTF-8. To minimize the hassle and performance overhead of converting, you can now simply append a <code>u8<\/code> suffix to your string literals to get them in UTF-8 right away:<\/p>\n<pre><code class=\"language-c#\">var u8 = \"This is a UTF-8 string!\"u8;<\/code><\/pre>\n<p>UTF-8 string literals simply give you back a chunk of bytes &#8211; in the form of a <code>ReadOnlySpan&lt;byte&gt;<\/code>. For the scenarios where it&#8217;s important to have a UTF-8 encoding this is probably more useful than some dedicated new UTF-8 string type.<\/p>\n<p>Read the docs on <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/language-reference\/builtin-types\/reference-types#utf-8-string-literals\">UTF-8 string literals<\/a>.<\/p>\n<h2>Raw string literals<\/h2>\n<p>A lot of what gets put in string literals is &#8220;code&#8221; of some sort &#8211; not just program text, but also JSON and XML data, HTML, regular expressions, SQL queries, etc. It&#8217;s really unhelpful when many of the special characters that show up in such text have special meaning in C# string literals! Noteworthy examples include <code>\\<\/code> and <code>\"<\/code>, joined in interpolated strings by <code>{<\/code> and <code>}<\/code>. Having to escape all of those is a real bummer, and an ongoing source of pain an bugs.<\/p>\n<p>Why not have a form of string literals that has no escape characters at all? That&#8217;s what raw string literals are. Everything is content!<\/p>\n<p>A raw string literal is delimited by at least three double-quotes:<\/p>\n<pre><code class=\"language-c#\">var raw1 = \"\"\"This\\is\\all \"content\"!\"\"\";\r\nConsole.WriteLine(raw1);<\/code><\/pre>\n<p>This prints:<\/p>\n<pre><code class=\"language-cli\">This\\is\\all \"content\"!<\/code><\/pre>\n<p>If you need three or more <code>\"<\/code>s to be part of your content, you just use <em>more<\/em> <code>\"<\/code>s on the outside. The beginning and end just have to match:<\/p>\n<pre><code class=\"language-c#\">var raw2 = \"\"\"\"\"I can do \", \"\", \"\"\" or even \"\"\"\" double quotes!\"\"\"\"\";<\/code><\/pre>\n<p>This makes it really easy to paste in, maintain and read at a glance what the literal contains.<\/p>\n<p>Multi-line raw string literals can also truncate leading white space: The position of the end quote determines where white space starts to be included in the output:<\/p>\n<pre><code class=\"language-c#\">var raw3 = \"\"\"\r\n    &lt;element attr=\"content\"&gt;\r\n      &lt;body&gt;\r\n        This line is indented by 4 spaces.\r\n      &lt;\/body&gt;\r\n    &lt;\/element&gt;\r\n    \"\"\";\r\n\/\/  ^white space left of here is removed<\/code><\/pre>\n<p>Since there are four spaces to the left of the end quote, four spaces will be removed from the beginning of every line of content, yielding this output:<\/p>\n<pre><code class=\"language-html\">&lt;element attr=\"content\"&gt;\r\n  &lt;body&gt;\r\n    This line is indented by 4 spaces.\r\n  &lt;\/body&gt;\r\n&lt;\/element&gt;<\/code><\/pre>\n<p>There&#8217;s much more to raw string literals than this &#8211; for instance they support interpolation! Read more about <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/programming-guide\/strings\/#raw-string-literals\">raw string literals<\/a> in the docs. <\/p>\n<h2>Abstracting over static members<\/h2>\n<p>How do you abstract over operations that are inherently static &#8211; such as operators? The traditional answer is &#8220;poorly&#8221;. In C# 11 we released support for static virtual members in interfaces, which was in preview in C# 10. With this you can now define a very simple mathematical interface:<\/p>\n<pre><code class=\"language-c#\">public interface IMonoid&lt;TSelf&gt; where TSelf : IMonoid&lt;TSelf&gt;\r\n{\r\n    public static abstract TSelf operator +(TSelf a, TSelf b);\r\n    public static abstract TSelf Zero { get; }\r\n}<\/code><\/pre>\n<p>Notice how the interface takes a type parameter for &#8220;itself&#8221;. That&#8217;s because static members don&#8217;t have a <code>this<\/code>. <\/p>\n<p>Anyone can now implement this interface by providing implementations for the two static members, and passing themselves as the <code>TSelf<\/code> type argument:<\/p>\n<pre><code class=\"language-c#\">public struct MyInt : IMonoid&lt;MyInt&gt;\r\n{\r\n    int value;\r\n    public MyInt(int i) =&gt; value = i;\r\n    public static MyInt operator +(MyInt a, MyInt b) =&gt; new MyInt(a.value + b.value);\r\n    public static MyInt Zero =&gt; new MyInt(0);\r\n}<\/code><\/pre>\n<p>Importantly, how do you <em>consume<\/em> these abstract operations? How do you call virtual members when there is no instance to call them on? The answer is via generics. Here is what it looks like:<\/p>\n<pre><code class=\"language-c#\">T AddAll&lt;T&gt;(params T[] elements) where T : IMonoid&lt;T&gt;\r\n{\r\n    T result = T.Zero;\r\n    foreach (var element in elements)\r\n    {\r\n        result += element;\r\n    }\r\n    return result;\r\n}<\/code><\/pre>\n<p>The type parameter <code>T<\/code> is constrained by the <code>IMonoid&lt;T&gt;<\/code> interface, and that allows the static virtual members of that interface &#8211; <code>Zero<\/code> and <code>+<\/code> &#8211; to be called on <code>T<\/code> itself! <\/p>\n<p>Now we can call the generic method with some <code>MyInt<\/code>s, and the correct implementations of <code>+<\/code> and <code>Zero<\/code> are passed in through the type argument:<\/p>\n<pre><code class=\"language-c#\">MyInt sum = AddAll&lt;MyInt&gt;(new MyInt(3), new MyInt(4), new MyInt(5));<\/code><\/pre>\n<p>In fact .NET 7 comes with a new namespace <code>System.Numerics<\/code> chock-full of math interfaces, representing the different combinations of operators and other static members that you&#8217;d ever want to use: the &#8220;grown-up&#8221; versions of the little <code>IMonoid&lt;T&gt;<\/code> interface above. All the numeric types in .NET now implement these new interfaces &#8211; and you can add them for your own types too! So it&#8217;s now easy to write numeric algorithms once and for all &#8211; abstracted from the concrete types they work on &#8211; instead of having forests of overloads containing essentially the same code.<\/p>\n<p>It&#8217;s also worth noting that static virtual members are useful for other things than math. For instance you can abstract over factory methods for a hierarchy of types. But we&#8217;ve covered enough for now &#8211; you might want to check out these tutorials in docs on <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/whats-new\/tutorials\/static-virtual-interface-members#static-abstract-interface-methods\">static abstract interface methods<\/a> and <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/whats-new\/tutorials\/static-virtual-interface-members#generic-math\">generic math<\/a>.<\/p>\n<p>Even if you do not create interfaces with static virtual members, you benefit from the improvements they make to .NET libraries, now and in the future.<\/p>\n<h2>List patterns<\/h2>\n<p>Pattern matching is one of the ongoing stories in C# that we just keep filling out. Pattern matching was introduced in C# 7 and since then it has grown to become one of the most important and powerful control structures in the language.<\/p>\n<p>C# 11 adds <em>list patterns<\/em> to the story. With list patterns you can apply patterns recursively to the individual elements of list-like input &#8211; or to a range of them. Let&#8217;s jump right in with the generic algorithm from above, rewritten as a recursive method using list patterns:<\/p>\n<pre><code class=\"language-c#\">T AddAll&lt;T&gt;(params T[] elements) where T : IMonoid&lt;T&gt; =&gt; \r\n    elements switch\r\n{\r\n    [] =&gt; T.Zero,\r\n    [var first, ..var rest] =&gt; first + AddAll&lt;T&gt;(rest),\r\n};<\/code><\/pre>\n<p>There&#8217;s a lot going on, but at the center is a switch expression with two cases. One case returns zero for an empty list <code>[]<\/code>, where <code>Zero<\/code> is defined by the interface. The other case extracts the first element into <code>first<\/code> with the <code>var first<\/code> pattern, and the remainder is extracted into <code>rest<\/code> using the <code>..<\/code> to slice out all the remaining elements into the <code>var rest<\/code> pattern.<\/p>\n<p>Read more about <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/language-reference\/operators\/patterns#list-patterns\">list patterns<\/a> in the docs.<\/p>\n<h2>Required members<\/h2>\n<p>Another ongoing theme that we&#8217;ve been working on for several releases is improving object creation and initialization.  C# 11 continues these improvements with <em>required members<\/em>.<\/p>\n<p>When creating types that used object initializers, you used to be unable to specify that some properties must be initialized. Now, you can say that a property or field is <code>required<\/code>. This means that it <em>must<\/em> be initialized by an object initializer when an object of the type is created:<\/p>\n<pre><code class=\"language-c#\">public class Person\r\n{\r\n    public required string FirstName { get; init; }\r\n    public string? MiddleName { get; init; }\r\n    public required string LastName { get; init; }\r\n}<\/code><\/pre>\n<p>It is now an error to create a <code>Person<\/code> without initializing both the required properties:<\/p>\n<pre><code class=\"language-c#\">var person = new Person { FirstName = \"Ada\" }; \/\/ Error: no LastName!<\/code><\/pre>\n<p>Check the docs for more on <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/language-reference\/keywords\/required\">required members<\/a>.<\/p>\n<h2>In closing &#8230;<\/h2>\n<p>C# 11 also includes many other features. I hope this appetizer excites you to explore <a href=\"https:\/\/learn.microsoft.com\/dotnet\/csharp\/whats-new\/csharp-11\">What&#8217;s new in C# 11<\/a> and that you have as much fun coding with C# 11 as we had making it! We strive to make the language ever more useful, not only by adding more expressive power (as with static virtual members) but also by simplifying, streamlining and removing boilerplate (as with e.g. raw string literals and list patterns) and making it safer (as with required members).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C# 11 is here! Bringing with it some highly anticipated features including string literals, generic math, required members, and much more.<\/p>\n","protected":false},"author":1379,"featured_media":43242,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[685,756],"tags":[7611,7601],"class_list":["post-43180","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dotnet","category-csharp","tag-dotnet-7","tag-c-11"],"acf":[],"blog_post_summary":"<p>C# 11 is here! Bringing with it some highly anticipated features including string literals, generic math, required members, and much more.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/43180","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/1379"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=43180"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/43180\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/43242"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=43180"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=43180"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=43180"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}