<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Mark Zhou's Tech Blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/mazhou/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/mazhou/feed.xml</link>
    <description>The developer who works for developers</description>
    <lastBuildDate>Sun, 25 Mar 2018 21:17:32 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>C# 7 Series, Part 10: Span&lt;T&gt; and universal memory management</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-10-spant-and-universal-memory-management</link>
      <pubDate>Sun, 25 Mar 2018 13:00:50 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=545</guid>
      <description><![CDATA[Part 1: Value TuplesPart 2: Async MainPart 3: Default LiteralsPart 4: DiscardsPart 5: Private...]]></description>
      <content:encoded><![CDATA[<p><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/">Part 1: Value Tuples</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main/">Part 2: Async Main</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/06/c-7-series-part-3-default-literals/">Part 3: Default Literals</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/">Part 4: Discards</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/10/05/c-7-series-part-5-private-protected/">Part 5: Private Protected</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/11/21/c-7-series-part-6-read-only-structs/">Part 6: Read-only structs</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/12/12/c-7-series-part-7-ref-returns/">Part 7: Ref Returns</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2018/01/08/c-7-series-part-8-in-parameters/">Part 8: “in” Parameters</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2018/03/02/c-7-series-part-9-ref-structs/">Part 9: ref structs</a><br>Part 10: (This post) Span&lt;T&gt; and universal memory management</p><h3>Background</h3><p>.NET is a managed platform, that means the memory access and management is safe and automatic. All types are fully managed by .NET, it allocates memory either on the execution stacks, or managed heaps. </p><p>In the event of interop or low-level development, you may want the access to the native objects and system memory, here is why the interop part comes, there are types that can marshal into the native world, invoke native APIs, convert managed/native types and define a native structure from the managed code.</p><h4>Problem 1: Memory access patterns</h4><p>In .NET world, there are three types of memory you may be interested:</p><ul><li>Managed heap memory, such as an array;</li><li>Stack memory, such as objects created by <code>stackalloc</code>;</li><li>Native memory, such as a native pointer reference.</li></ul><p>Each type of memory access may need to use language features that are designed for it:</p><ul><li>To access heap memory, use the <code>fixed</code> (pinned) pointer on supported types (like <code>string</code>), or use other appropriate .NET types that have access to it, such as an array or a buffer;</li><li>To access stack memory, use pointers with <code>stackalloc</code>;</li><li>To access unmanaged system memory, use pointers with <code>Marshal</code> APIs.</li></ul><p>You see, different access pattern needs different code, no single built-in type for all contiguous memory access.</p><h4>Problem 2: Performance</h4><p>In many applications, the most CPU consuming operations are string operations. If you run a profiler session against your application, you may find the fact that 95% of the CPU time is used to call string and related functions. </p><p><code>Trim</code>, <code>IsNullOrWhiteSpace</code>, and <code>SubString</code> may be the most frequently used string APIs, and they are also very heavy:</p><ul><li><code>Trim()</code> or <code>SubString()</code> returns a new string object that is part of the original string, this is unnecessary if there is a way to slice and return a portion of the original string to save one copy.</li><li><code>IsNullOrWhiteSpace()</code> takes a string object that needs a memory copy (because string is immutable.)</li><li>Specifically,&nbsp; string concatenation is expensive, it takes <code>n</code> string objects, makes <code>n</code> copy, generate <code>n - 1</code> temporary string objects, and return a final string object, the <code>n – 1</code> copies can be eliminated if there is a way to get direct access to the return string memory and perform sequential writes.</li></ul><h3>Span&lt;T&gt;</h3><p><code>System.Span&lt;T&gt;</code> is a stack-only type (<code>ref struct</code>) that wraps all memory access patterns, it is the type for universal contiguous memory access. You can think the implementation of the Span&lt;T&gt; contains a dummy reference and a length, accepting all 3 memory access types.</p><p>You can create a Span&lt;T&gt; using its constructor overloads or implicit operators from array, stackalloc’d pointers and unmanaged pointers. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: green">// Use implicit operator Span&lt;char&gt;(char[]).<br></span><span>Span</span>&lt;<span style="color: blue">char</span>&gt; span1 = <span style="color: blue">new</span>&nbsp;<span style="color: blue">char</span>[] { <span>'s'</span>, <span>'p'</span>, <span>'a'</span>, <span>'n'</span> };<br><br><span style="color: green">// Use stackalloc.<br></span><span>Span</span>&lt;<span style="color: blue">byte</span>&gt; span2 = <span style="color: blue">stackalloc</span>&nbsp;<span style="color: blue">byte</span>[50];<br><br><span style="color: green">// Use constructor.<br></span><span>IntPtr</span> array = <span style="color: blue">new</span>&nbsp;<span>IntPtr</span>();<br><span>Span</span>&lt;<span style="color: blue">int</span>&gt; span3 = <span style="color: blue">new</span>&nbsp;<span>Span</span>&lt;<span style="color: blue">int</span>&gt;(array.ToPointer(), 1);</pre><p>Once you have a Span&lt;T&gt; object, you can set value with a specified index, or return a portion of the span:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: green">// Create an instance.<br></span><span>Span</span>&lt;<span style="color: blue">char</span>&gt; span = <span style="color: blue">new</span>&nbsp;<span style="color: blue">char</span>[] { <span>'s'</span>, <span>'p'</span>, <span>'a'</span>, <span>'n'</span> };<br><span style="color: green">// Access the reference of the first element.<br></span><span style="color: blue">ref</span>&nbsp;<span style="color: blue">char</span> first = <span style="color: blue">ref</span> span[0];<br><span style="color: green">// Assign the reference with a new value.<br></span>first = <span>'S'</span>;<br><span style="color: green">// You get "Span".<br></span><span>Console</span>.WriteLine(span.ToArray());</pre><pre style="background: white;color: black;font-family: consolas"><span style="color: green">// Return a new span with start index = 1 and end index = span.Length - 1.<br></span><span style="color: green">// You get "pan".<br></span><span>Span</span>&lt;<span style="color: blue">char</span>&gt; span2 = span.Slice(1);<br><span>Console</span>.WriteLine(span2.ToArray());</pre><p>You can then use the <code>Slice()</code> method to write a high performance <code>Trim()</code> method:</p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> test = <span>"&nbsp;&nbsp; Hello, World! "</span>;<br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(Trim(test.ToCharArray()).ToArray());<br>}<br><br><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span>Span</span>&lt;<span style="color: blue">char</span>&gt; Trim(<span>Span</span>&lt;<span style="color: blue">char</span>&gt; source)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (source.IsEmpty)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> source;<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> start = 0, end = source.Length - 1;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">char</span> startChar = source[start], endChar = source[end];<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">while</span> ((start &lt; end) &amp;&amp; (startChar == <span>' '</span> || endChar == <span>' '</span>))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (startChar == <span>' '</span>)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; start++;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (endChar == <span>' '</span>)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end—;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; startChar = source[start];<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; endChar = source[end];<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> source.Slice(start, end - start + 1);<br>}</pre><p>The above code does not copy over strings, nor generate new strings, it returns a portion of the original string by calling the <code>Slice()</code> method.</p><p>Because Span&lt;T&gt; is a ref struct, all ref struct restrictions apply. i.e. you cannot use Span&lt;T&gt; in fields, properties, iterator and async methods.</p><h3>Memory&lt;T&gt;</h3><p><code>System.Memory&lt;T&gt;</code> is a wrapper of <code>System.Span&lt;T&gt;</code>, make it accessible in iterator and async methods. Use the <code>Span</code> property on the Memory&lt;T&gt; to access the underlying memory, this is extremely helpful in the asynchronous scenarios like File Streams and network communications (<code>HttpClient</code> etc..) </p><p>The following code shows simple usage of this type. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">async</span>&nbsp;<span>Task</span> Main(<span style="color: blue">string</span>[] args)<br>{<br>&nbsp;&nbsp;&nbsp; <span>Memory</span>&lt;<span style="color: blue">byte</span>&gt; memory = <span style="color: blue">new</span>&nbsp;<span>Memory</span>&lt;<span style="color: blue">byte</span>&gt;(<span style="color: blue">new</span>&nbsp;<span style="color: blue">byte</span>[50]);<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> count = <span style="color: blue">await</span> ReadFromUrlAsync(<span>"https://www.microsoft.com"</span>, memory).ConfigureAwait(<span style="color: blue">false</span>);<br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>"Bytes written: {0}"</span>, count);<br>}<br><br><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">async</span>&nbsp;<span>ValueTask</span>&lt;<span style="color: blue">int</span>&gt; ReadFromUrlAsync(<span style="color: blue">string</span> url, <span>Memory</span>&lt;<span style="color: blue">byte</span>&gt; memory)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">using</span> (<span>HttpClient</span> client = <span style="color: blue">new</span>&nbsp;<span>HttpClient</span>())<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Stream</span> stream = <span style="color: blue">await</span> client.GetStreamAsync(<span style="color: blue">new</span>&nbsp;<span>Uri</span>(url)).ConfigureAwait(<span style="color: blue">false</span>);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span>&nbsp;<span style="color: blue">await</span> stream.ReadAsync(memory).ConfigureAwait(<span style="color: blue">false</span>);<br>&nbsp;&nbsp;&nbsp; }<br>}</pre><p>The Framework Class Library/Core Framework (FCL/CoreFx) will add APIs based on the span-like types for Streams, strings and more in .NET Core 2.1.</p><h3>ReadOnlySpan&lt;T&gt; and ReadOnlyMemory&lt;T&gt;</h3><p><code>System.ReadOnlySpan&lt;T&gt;</code> is the read-only version of the <code>System.Span&lt;T&gt;</code> struct where the indexer returns a <code>readonly ref</code> object instead of <code>ref</code> object. You get read-only memory access when using <code>System.ReadOnlySpan&lt;T&gt;</code> <code>readonly ref</code> struct.</p><p>This is useful for <code>string</code> type, because string is immutable, it is treated as read-only span.</p><p>We can rewrite the above code to implement the <code>Trim()</code> method using ReadOnlySpan&lt;T&gt;:</p><pre style="color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// Implicit operator ReadOnlySpan(string).<br></span>&nbsp;&nbsp;&nbsp; <span>ReadOnlySpan</span>&lt;<span style="color: blue">char</span>&gt; test = <span>"&nbsp;&nbsp; Hello, World! "</span>;<br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(Trim(test).ToArray());<br>}<br><br><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span>ReadOnlySpan</span>&lt;<span style="color: blue">char</span>&gt; Trim(<span>ReadOnlySpan</span>&lt;<span style="color: blue">char</span>&gt; source)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (source.IsEmpty)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> source;<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> start = 0, end = source.Length - 1;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">char</span> startChar = source[start], endChar = source[end];<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">while</span> ((start &lt; end) &amp;&amp; (startChar == <span>' '</span> || endChar == <span>' '</span>))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (startChar == <span>' '</span>)<br>&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; start++;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (endChar == <span>' '</span>)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end—;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; startChar = source[start];<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; endChar = source[end];<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> source.Slice(start, end - start + 1);<br>}</pre><p>As you can see, Nothing is changed in the method body; I just changed the parameter type from <code>Span&lt;T&gt;</code> to <code>ReadOnlySpan&lt;T&gt;</code>, and used the implicit operator to convert a <code>string</code> literal to <code>ReadOnlySpan&lt;char&gt;</code>.</p><p><code>System.ReadOnlyMemory&lt;T&gt;</code> is the read-only version of <code>System.Memory&lt;T&gt;</code> struct where the <code>Span</code> property is a <code>ReadOnlySpan&lt;T&gt;</code>. When using this type, you get read-only access to the memory and you can use it with an iterator method or async method.</p><h3>Memory Extensions</h3><p>The <code>System.MemoryExtensions</code> class contains extension methods for different types that manipulates with span types, here is a list of commonly used extension methods, many of them are the equivalent implementations for existing APIs using the span types.</p><ul><li><strong>AsSpan, AsMemory</strong>: Convert arrays into Span&lt;T&gt; or Memory&lt;T&gt; or their read-only counterparts.</li><li><strong>BinarySearch, IndexOf, LastIndexOf</strong>: Search elements and indexes.</li><li><strong>IsWhiteSpace, Trim, TrimStart, TrimEnd, ToUpper, ToUpperInvariant, ToLower, ToLowerInvariant</strong>: <code>Span&lt;char&gt;</code> operations similar to <code>string</code>.</li></ul><h3>Memory Marshal</h3><p>In some case, you probably want to have lower level access to the memory types and system buffers, and convert between spans and read-only spans. The <code>System.Runtime.InteropServices.MemoryMarshal</code> static class provides such functionalities to allow you control these access scenarios. The following code shows to title case a string using the span types, this is high performant because there is no temporary string allocations.</p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> source = <span>"span like types are awesome!"</span>;<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// source.ToMemory() converts source from string to ReadOnlyMemory&lt;char&gt;,<br></span>&nbsp;&nbsp;&nbsp; <span style="color: green">// and MemoryMarshal.AsMemory converts ReadOnlyMemory&lt;char&gt; to Memory&lt;char&gt;<br></span>&nbsp;&nbsp;&nbsp; <span style="color: green">// so you can modify the elements.<br></span>&nbsp;&nbsp;&nbsp; TitleCase(<span>MemoryMarshal</span>.AsMemory(source.AsMemory()));<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// You get "Span like types are awesome!";<br></span>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(source);<br>}<br><br><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> TitleCase(<span>Memory</span>&lt;<span style="color: blue">char</span>&gt; memory)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (memory.IsEmpty)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span>;<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">ref</span>&nbsp;<span style="color: blue">char</span> first = <span style="color: blue">ref</span> memory.Span[0];<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (first &gt;= <span>'a'</span> &amp;&amp; first &lt;= <span>'z'</span>)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; first = (<span style="color: blue">char</span>)(first - 32);<br>&nbsp;&nbsp;&nbsp; }<br>}</pre><h3>Conclusion</h3><p>Span&lt;T&gt; and Memory&lt;T&gt; enables a uniform way to access contiguous memory, regardless how the memory is allocated. It is very helpful for native development scenarios, as well as high performance scenarios. Especially, you will gain significant performance improvements while using span types to work with strings. It is a very nice feature innovated in C# 7.2.</p><p>NOTE: To use this feature, you will need to use Visual Studio 2017.5 and language version 7.2 or latest.</p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 9: ref structs</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-9-ref-structs</link>
      <pubDate>Fri, 02 Mar 2018 04:48:00 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=525</guid>
      <description><![CDATA[Part 1: Value TuplesPart 2: Async MainPart 3: Default LiteralsPart 4: DiscardsPart 5: Private...]]></description>
      <content:encoded><![CDATA[<p><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/">Part 1: Value Tuples</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main/">Part 2: Async Main</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/06/c-7-series-part-3-default-literals/">Part 3: Default Literals</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/">Part 4: Discards</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/10/05/c-7-series-part-5-private-protected/">Part 5: Private Protected</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/11/21/c-7-series-part-6-read-only-structs/">Part 6: Read-only structs</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/12/12/c-7-series-part-7-ref-returns/">Part 7: Ref Returns</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2018/01/08/c-7-series-part-8-in-parameters/">Part 8: “in” Parameters</a><br>Part 9: (This post) ref structs</p><h3>Background</h3><p>In the previous posts, I have explained many new C# features, each of the feature is introduced to either enhance the language, or solve issues. Specifically, I explained value types and reference types, pass parameters by value, pass parameters by reference, ref locals and ref returns and <code>in</code> parameters. Many of these features are designed for high performance scenarios. </p><p><code>ref</code> and <code>in</code> parameters can help to avoid copying values so that it reduces the allocation of memory. This is efficient when you have stack allocated local variables to pass as the actual parameters of a method, in this case, all the allocations are on the stack; no heap allocation is necessary. </p><p>For high performance and native development scenarios, you may want “stack-only”&nbsp; types that always stay on execution stack, so operations against objects of this type can only happen on the stack, any external references to this type in the scopes that may expose to managed heap, should be disallowed. </p><h3>Ref Struct</h3><p><code>ref struct</code> is the stack-only value type that:</p><ul><li>Represents a sequential struct layout;</li><li>Can be used stack-only. i.e. method parameters and local variables;</li><li>Cannot be static or instance members of a class or normal struct;</li><li>Cannot be method parameter of async methods or lambda expressions;</li><li>Cannot be dynamic binding, boxing, unboxing, wrapping or converting.</li></ul><p><code>ref struct</code> is also called embedded reference.</p><h3>Examples</h3><p>The following code defines a ref struct.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">ref</span>&nbsp;<span style="color: blue">struct</span>&nbsp;<span>MyRefStruct<br></span>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">int</span> MyIntValue1;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">int</span> MyIntValue2;<br><br>    [<span>EditorBrowsable</span>(<span>EditorBrowsableState</span>.Never)]<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">override</span>&nbsp;<span style="color: blue">bool</span> Equals(<span style="color: blue">object</span> obj) =&gt; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>NotSupportedException</span>();<br><br>&nbsp;&nbsp;&nbsp; [<span>EditorBrowsable</span>(<span>EditorBrowsableState</span>.Never)]<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">override</span>&nbsp;<span style="color: blue">int</span> GetHashCode() =&gt; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>NotSupportedException</span>();<br><br>&nbsp;&nbsp;&nbsp; [<span>EditorBrowsable</span>(<span>EditorBrowsableState</span>.Never)]<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">override</span>&nbsp;<span style="color: blue">string</span> ToString() =&gt; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>NotSupportedException</span>();<br>}</pre><p>Please note, I have overridden the Equals, GetHashCode and ToString methods that are inherited from <code>System.Object</code>.&nbsp; Because boxing is not allowed for ref structs, you will have no way to call these two base methods.</p><p>You can use <code>MyRefStruct</code> as regular value type in method parameters or local variables, but you will not be able to use it elsewhere. </p><p><a href="https://msdnshared.blob.core.windows.net/media/2018/03/image3.png"><img width="671" height="296" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2018/03/image_thumb2.png" border="0"></a></p><p><a href="https://msdnshared.blob.core.windows.net/media/2018/03/image4.png"><img width="671" height="265" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2018/03/image_thumb3.png" border="0"></a></p><p>You can also make readonly ref structs, simply add readonly directive to the ref struct declaration. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">readonly</span>&nbsp;<span style="color: blue">ref</span>&nbsp;<span style="color: blue">struct</span>&nbsp;<span>MyRefStruct<br></span>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">readonly</span>&nbsp;<span style="color: blue">int</span> MyIntValue1;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">readonly</span>&nbsp;<span style="color: blue">int</span> MyIntValue2;<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> MyRefStruct(<span style="color: blue">int</span> value1, <span style="color: blue">int</span> value2)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.MyIntValue1 = value1;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.MyIntValue2 = value2;<br>&nbsp;&nbsp;&nbsp; }<br><br>    [<span>EditorBrowsable</span>(<span>EditorBrowsableState</span>.Never)]<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">override</span>&nbsp;<span style="color: blue">bool</span> Equals(<span style="color: blue">object</span> obj) =&gt; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>NotSupportedException</span>();<br><br>&nbsp;&nbsp;&nbsp; [<span>EditorBrowsable</span>(<span>EditorBrowsableState</span>.Never)]<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">override</span>&nbsp;<span style="color: blue">int</span> GetHashCode() =&gt; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>NotSupportedException</span>();<br><br>&nbsp;&nbsp;&nbsp; [<span>EditorBrowsable</span>(<span>EditorBrowsableState</span>.Never)]<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">override</span>&nbsp;<span style="color: blue">string</span> ToString() =&gt; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>NotSupportedException</span>();<br>}</pre><p>Like regular readonly structs, you need to make all instance fields/properties read-only.</p><h3>Metadata</h3><p>Ref struct is available in C# 7.2. This feature needs compiler level changes to work, to be backward compatible with previously&nbsp; compiler generated assemblies,. C# 7.2 compiler emits [Obsolete] and [IsByRefLike] attributes for ref struct declarations. </p><p>If any old assemblies references library that contains ref struct types, the [Obsolete] attribute will effect and block the code from compiling. </p><p>Here is the generated IL for the above ref struct declaration.</p><p><pre>.class public <font>sequential</font> ansi sealed beforefieldinit Demo.MyRefStruct<br>extends [System.Runtime]System.ValueType<br>{<br>.custom instance void [System.Runtime]System.Runtime.CompilerServices.<font>IsByRefLikeAttribute</font>::.ctor() = (<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 01 00 00 00<br>&nbsp;&nbsp;&nbsp; )<br>.custom instance void [System.Runtime]System.<font>ObsoleteAttribute</font>::.ctor(string, bool) = (<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 69 6c 65 72 2e 01 00 00<br>&nbsp;&nbsp;&nbsp; )<br>.custom instance void [System.Runtime]System.Runtime.CompilerServices.<font>IsReadOnlyAttribute</font>::.ctor() = (<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 01 00 00 00<br>&nbsp;&nbsp;&nbsp; )<br>// Fields<br>.field public initonly int32 MyIntValue1<br>.field public initonly int32 MyIntValue2<br>// Methods<br>.method public hidebysig specialname rtspecialname<br>instance void .ctor (<br>int32 value1,<br>int32 value2<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ) cil managed<br>&nbsp;&nbsp;&nbsp; {<br>// Method begins at RVA 0x2090<br>// Code size 16 (0x10)<br>.maxstack 8<br>// (no C# code)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0000: nop<br>// this.MyIntValue1 = value1;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0001: ldarg.0<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0002: ldarg.1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0003: stfld int32 Demo.MyRefStruct::MyIntValue1<br>// this.MyIntValue2 = value2;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0008: ldarg.0<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0009: ldarg.2<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_000a: stfld int32 Demo.MyRefStruct::MyIntValue2<br>// (no C# code)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_000f: ret<br>&nbsp;&nbsp;&nbsp; } // end of method MyRefStruct::.ctor<br>.method public hidebysig virtual<br>instance bool Equals (<br>object obj<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ) cil managed<br>&nbsp;&nbsp;&nbsp; {<br>// Method begins at RVA 0x20a1<br>// Code size 6 (0x6)<br>.maxstack 8<br>// throw new NotSupportedException();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0000: newobj instance void [System.Runtime]System.NotSupportedException::.ctor()<br>// (no C# code)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0005: throw<br>&nbsp;&nbsp;&nbsp; } // end of method MyRefStruct::Equals<br>.method public hidebysig virtual<br>instance int32 GetHashCode () cil managed<br>&nbsp;&nbsp;&nbsp; {<br>.custom instance void [System.Runtime]System.ComponentModel.EditorBrowsableAttribute::.ctor(valuetype [System.Runtime]System.ComponentModel.EditorBrowsableState) = (<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 01 00 01 00 00 00 00 00<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br>// Method begins at RVA 0x20a8<br>// Code size 6 (0x6)<br>.maxstack 8<br>// throw new NotSupportedException();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0000: newobj instance void [System.Runtime]System.NotSupportedException::.ctor()<br>// (no C# code)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0005: throw<br>&nbsp;&nbsp;&nbsp; } // end of method MyRefStruct::GetHashCode<br>.method public hidebysig virtual<br>instance string ToString () cil managed<br>&nbsp;&nbsp;&nbsp; {<br>.custom instance void [System.Runtime]System.ComponentModel.EditorBrowsableAttribute::.ctor(valuetype [System.Runtime]System.ComponentModel.EditorBrowsableState) = (<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 01 00 01 00 00 00 00 00<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br>// Method begins at RVA 0x20af<br>// Code size 6 (0x6)<br>.maxstack 8<br>// throw new NotSupportedException();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0000: newobj instance void [System.Runtime]System.NotSupportedException::.ctor()<br>// (no C# code)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IL_0005: throw<br>&nbsp;&nbsp;&nbsp; } // end of method MyRefStruct::ToString<br>} // end of class Demo.MyRefStruct</pre><h3>Span&lt;T&gt; and Memory&lt;T&gt;</h3><p>With the support of ref-like types, it is now possible to have a consolidated type for all contiguous memory access. The <code>System.Span&lt;T&gt;</code>, which represents a sequential space of the memory, can be used for universal memory operations for execution stacks, managed heaps and unmanaged heaps.</p><p>Here is a simple usage of <code>ReadOnlySpan&lt;T&gt;</code> to trim the start spaces of a string.</p><p><pre style="background: white;color: black;font-family: consolas"><p><span style="color: blue">internal</span>&nbsp;<span style="color: blue">class</span>&nbsp;<span>Program<br></span>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> text = <span>"&nbsp; I am using C# 7.2 Span&lt;T&gt;!"</span>;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(TrimStart(text).ToArray());<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span>ReadOnlySpan</span>&lt;<span style="color: blue">char</span>&gt; TrimStart(<span>ReadOnlySpan</span>&lt;<span style="color: blue">char</span>&gt; text)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (text.IsEmpty)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> text;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> i = 0;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">char</span> c;<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">while</span> ((c = text[i]) == <span>' '</span>)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i++;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> text.Slice(i);<br>&nbsp;&nbsp;&nbsp; }<br>}</p></pre><p><code>System.Memory&lt;T&gt;</code> wraps the <code>System.Span&lt;T&gt;</code> so it can be used for async methods, which enables asynchronous scenarios for I/O bound and CPU bound operations. My next post will have more details.</p><h3>Conclusion</h3><p> C# 7.2 adds language features for high performance scenarios and enables efficiencies for lower native development and interoperability scenarios. Ref struct can also be used together with stackalloc, Span&lt;T&gt;, fixed buffers and Ranges (C# 7.3) for productivity. </p><p><strong>NOTE:</strong> To use this feature, use Visual Studio 2017 15.5+.</p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 8: “in” Parameters</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-8-in-parameters</link>
      <pubDate>Mon, 08 Jan 2018 04:06:50 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=475</guid>
      <description><![CDATA[C# 7 SeriesPart 1: Value TuplesPart 2: Async MainPart 3: Default LiteralsPart 4: DiscardsPart 5:...]]></description>
      <content:encoded><![CDATA[<p><strong>C# 7 Series</strong></p><p><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/">Part 1: Value Tuples</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main/">Part 2: Async Main</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/06/c-7-series-part-3-default-literals/">Part 3: Default Literals</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/">Part 4: Discards</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/10/05/c-7-series-part-5-private-protected/">Part 5: Private Protected</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/11/21/c-7-series-part-6-read-only-structs/">Part 6: Read-only structs</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/12/12/c-7-series-part-7-ref-returns/">Part 7: Ref Returns</a><br>Part 8: (This post) “in” Parameters</p><h3>Background</h3><p>By default, method arguments are passed by value. That is, arguments are copied and passed into the method. Therefore, modification to the argument inside the method body does not affect the original value. In most of the cases, modifications are unnecessary. </p><p>Other programming languages, such as C++, has a <code>const</code> parameter or similar concept: This indicates that the parameter inside the method body is a constant that cannot be reassigned. It helps to avoid mistakes where you unintentionally reassign a method parameter in the body, and improves the performance by disallowing the unnecessary assignments.</p><p>C# 7.2 introduces the <code>in</code> parameter (aka. <code>readonly ref</code> parameter.) A method parameter with <code>in</code> modifier means that this parameter is by ref and read only within the method body. </p><h3><code>in</code> parameters</h3><p>Let’s take the following method definition as an example.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">int</span> Increment(<span style="color: blue">int</span> value)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// Reassignment is ok, "value" is passed by value.<br></span>&nbsp;&nbsp;&nbsp; value = value + 1;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> value;<br>}</pre><p>To make a readonly ref parameter, use the <code>in</code> modifier for a parameter. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">int</span> Increment(<span style="color: blue">in</span>&nbsp;<span style="color: blue">int</span> value)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// Reassignment is not ok, "value" is passed by ref and read-only.<br></span>&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> returnValue = value + 1;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> returnValue;<br>}</pre><p>If you reassign value, the compiler will generate an error.</p><p><a href="https://msdnshared.blob.core.windows.net/media/2018/01/image84.png"><img width="503" height="162" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2018/01/image_thumb84.png" border="0"></a></p><p>To call this method, use your normal way. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">int</span> v = 1;<br><span>Console</span>.WriteLine(Increment(v));</pre><p>Because <code>value</code> is read-only, you cannot put <code>value</code> in the left side (I.e. <strong>LValue.</strong>) Unary operators that does an assignment is also disallowed, such as <code>++</code> or <code>–</code>. However, you can still take the address of the <code>value</code> and modify using pointer operations. </p><h3>Overload Resolutions</h3><p><code>in</code> is a modifier to a method parameter that indicates the ref kind of such parameter, it is considered as part of the method signature. That means you can have two method overloads that just differ by <code>in</code> modifier. </p><p>The following code example defines two method overloads, with just the ref kind different. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">class</span>&nbsp;<span>C<br></span>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">void</span> A(<span style="color: blue">int</span> a)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>"int a"</span>);<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">void</span> A(<span style="color: blue">in</span>&nbsp;<span style="color: blue">int</span> a)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>"in int a"</span>);<br>&nbsp;&nbsp;&nbsp; }<br>}</pre><p>By default, the method call will resolve to use by value signature. To clear the ambiguity and explicitly call the by ref signature, put <code>in</code> before the actual argument when explicitly call the <code>A(in int)</code> method overload.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{<br>&nbsp;&nbsp;&nbsp; <span>C</span> c = <span style="color: blue">new</span>&nbsp;<span>C</span>();<br>&nbsp;&nbsp;&nbsp; c.A(1); <span style="color: green">// A(int)<br></span>&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span> x = 1;<br>&nbsp;&nbsp;&nbsp; c.A(<span style="color: blue">in</span> x); <span style="color: green">// A(in int)<br></span>&nbsp;&nbsp;&nbsp; c.A(x); <span style="color: green">// A(int)<br></span>}</pre><p>The program output is as following.</p><p><a href="https://msdnshared.blob.core.windows.net/media/2018/01/image85.png"><img width="432" height="168" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2018/01/image_thumb85.png" border="0"></a></p><h3>Restrictions</h3><p>Since <code>in</code> parameters are read-only ref parameters, all ref parameter limitations apply.</p><ul><li>Cannot apply with an iterator method (I.e. method that has <code>yield</code> statements.)</li><li>Cannot apply with an async method</li><li>If you mark the <code>args</code> of the <code>Main</code> method as <code>in</code> modifier, the method signature will become invalid for the entry point.</li></ul><h3><code>in</code> parameter and the CLR</h3><p>.NET already has a similar concept in CLR, so the <code>in</code> parameter feature does not require CLR changes. </p><p>Any in parameter will be compiled to MSIL with an additional [in] directive in the definition. To observe the compilation behavior, I use ILDAsm.exe to get the decompiled MSIL for the above example. </p><p>The following MSIL code is for method C.A(int):</p><p><pre>.method public hidebysig instance void&nbsp; A(<font>int32</font> a) cil managed<br>
{<br>&nbsp;&nbsp; // Code size&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 13 (0xd)<br>&nbsp;&nbsp; .maxstack&nbsp; 8<br>&nbsp;&nbsp; IL_0000:&nbsp; nop<br>&nbsp;&nbsp; IL_0001:&nbsp; ldstr&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "int a"<br>&nbsp;&nbsp; IL_0006:&nbsp; call&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void [System.Console]System.Console::WriteLine(string)<br>&nbsp;&nbsp; IL_000b:&nbsp; nop<br>&nbsp;&nbsp; IL_000c:&nbsp; ret<br>
} // end of method C::A</pre><p>The following MSIL code is for method C.A(in int):</p><p><pre>.method public hidebysig instance void&nbsp; A(<font>[in] int32&amp;</font> a) cil managed<br>
{<br>&nbsp;&nbsp; .param [1]<br>&nbsp;&nbsp; .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) <br>&nbsp;&nbsp; // Code size&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 13 (0xd)<br>&nbsp;&nbsp; .maxstack&nbsp; 8<br>&nbsp;&nbsp; IL_0000:&nbsp; nop<br>&nbsp;&nbsp; IL_0001:&nbsp; ldstr&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "in int a"<br>&nbsp;&nbsp; IL_0006:&nbsp; call&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void [System.Console]System.Console::WriteLine(string)<br>&nbsp;&nbsp; IL_000b:&nbsp; nop<br>&nbsp;&nbsp; IL_000c:&nbsp; ret<br>
} // end of method C::A</pre><p>Do you see the difference? <code>int32&amp;</code> shows it is a by ref parameter; <code>[in]</code> is an additional metadata that instructs the CLR how to deal with this parameter.</p><p>The below code is the MSIL for the <code>Main</code> method in the above example, it shows how to call these two <code>C.A()</code> method overloads.</p><p><pre>.method private hidebysig static void&nbsp; Main(string[] args) cil managed<br>
{<br>&nbsp;&nbsp; .entrypoint<br>&nbsp;&nbsp; // Code size&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 35 (0x23)<br>&nbsp;&nbsp; .maxstack&nbsp; 2<br>&nbsp;&nbsp; .locals init (class Demo.C V_0,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32 V_1)<br>&nbsp;&nbsp; IL_0000:&nbsp; nop<br>&nbsp;&nbsp; IL_0001:&nbsp; newobj&nbsp;&nbsp;&nbsp;&nbsp; instance void Demo.C::.ctor()<br>&nbsp;&nbsp; IL_0006:&nbsp; stloc.0<br>&nbsp;&nbsp; IL_0007:&nbsp; ldloc.0<br>&nbsp;&nbsp; IL_0008:&nbsp; ldc.i4.1<br>&nbsp;&nbsp; IL_0009:&nbsp; callvirt&nbsp;&nbsp; instance void Demo.C::A(<font>int32</font>)<br>&nbsp;&nbsp; IL_000e:&nbsp; nop<br>&nbsp;&nbsp; IL_000f:&nbsp; ldc.i4.1<br>&nbsp;&nbsp; IL_0010:&nbsp; stloc.1<br>&nbsp;&nbsp; IL_0011:&nbsp; ldloc.0<br>&nbsp;&nbsp; IL_0012:&nbsp; ldloca.s&nbsp;&nbsp; V_1<br>&nbsp;&nbsp; IL_0014:&nbsp; callvirt&nbsp;&nbsp; instance void Demo.C::A(<font>int32&amp;</font>)<br>&nbsp;&nbsp; IL_0019:&nbsp; nop<br>&nbsp;&nbsp; IL_001a:&nbsp; ldloc.0<br>&nbsp;&nbsp; IL_001b:&nbsp; ldloc.1<br>&nbsp;&nbsp; IL_001c:&nbsp; callvirt&nbsp;&nbsp; instance void Demo.C::A(int32)<br>&nbsp;&nbsp; IL_0021:&nbsp; nop<br>&nbsp;&nbsp; IL_0022:&nbsp; ret<br>
} // end of method Program::Main</pre><p>From the call site, there is no additional metadata to instruct to call <code>C.A(in int)</code>.</p><h3><code>in</code> parameter and the Interop</h3><p>There are many places where the <code>[In]</code> attributes are used to match with the native method signature for the interoperability. Let’s take the following Windows API as an example.</p><p><pre style="background: white;color: black;font-family: consolas">[<span>DllImport</span>(<span>"shell32"</span>)]<br><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">extern</span>&nbsp;<span style="color: blue">int</span> ShellAbout(<br>&nbsp;&nbsp;&nbsp; [<span>In</span>] <span>IntPtr</span> handle,<br>&nbsp;&nbsp;&nbsp; [<span>In</span>] <span style="color: blue">string</span> title,<br>&nbsp;&nbsp;&nbsp; [<span>In</span>] <span style="color: blue">string</span> text,<br>&nbsp;&nbsp;&nbsp; [<span>In</span>] <span>IntPtr</span> icon);</pre><p>The corresponding MSIL for this method is as below.</p><p><pre>.method public hidebysig static pinvokeimpl("shell32" winapi) <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32&nbsp; ShellAbout([in] native int handle,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [in] string title,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [in] string text,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [in] native int icon) cil managed preservesig</pre><p>If we change the <code>ShellAbout</code> signature to use <code>in</code> parameter:</p><p><pre style="background: white;color: black;font-family: consolas">[<span>DllImport</span>(<span>"shell32"</span>)]<br><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">extern</span>&nbsp;<span style="color: blue">int</span> ShellAbout(<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">in</span>&nbsp;<span>IntPtr</span> handle,<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">in</span>&nbsp;<span style="color: blue">string</span> title,<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">in</span>&nbsp;<span style="color: blue">string</span> text,<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">in</span>&nbsp;<span>IntPtr</span> icon);</pre><p>The generated MSIL for this method is:</p><p><pre>.method public hidebysig static pinvokeimpl("shell32" winapi) <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32&nbsp; ShellAbout([in] native int&amp; handle,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [in] string&amp; title,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [in] string&amp; cext,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [in] native int&amp; icon) cil managed preservesig<br>
{<br>&nbsp;&nbsp; .param [1]<br>&nbsp;&nbsp; .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) <br>&nbsp;&nbsp; .param [2]<br>&nbsp;&nbsp; .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) <br>&nbsp;&nbsp; .param [3]<br>&nbsp;&nbsp; .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) <br>&nbsp;&nbsp; .param [4]<br>&nbsp;&nbsp; .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) <br>
}</pre><p>As you can see, the compiler emits code for each <code>in</code> parameter with <code>[in]</code> directive, ref data type and also <code>[IsReadOnly]</code> attribute. Since the parameter has changed from by value to by ref, the P/Invoke may fail due to the mismatch of the original signature. </p><h3>Conclusion</h3><p><code>in</code> parameter is a great feature that extends the C# language, it is easy to use and it is binary compatible (no CLR change required.) Read-only ref parameters help to avoid mistakes by giving a compile time error when modifying the read only parameter. This feature can be used with other ref features such as ref returns and ref structs. </p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 7: Ref Returns</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-7-ref-returns</link>
      <pubDate>Tue, 12 Dec 2017 23:12:42 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=426</guid>
      <description><![CDATA[C# 7 SeriesPart 1: Value TuplesPart 2: Async MainPart 3: Default LiteralsPart 4: DiscardsPart 5:...]]></description>
      <content:encoded><![CDATA[<p><strong>C# 7 Series</strong></p><p><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/">Part 1: Value Tuples</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main/">Part 2: Async Main</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/06/c-7-series-part-3-default-literals/">Part 3: Default Literals</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/">Part 4: Discards</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/10/05/c-7-series-part-5-private-protected/">Part 5: Private Protected</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/11/21/c-7-series-part-6-read-only-structs/">Part 6: Read-only structs</a><br>Part 7: (This post) Ref Returns</p><h3>Background</h3><p>There are two ways to pass an value into a method:</p><ol><li>Pass <strong>by value</strong>. When an argument is passed into a method, a copy of the argument (if it is a value type) or a copy of the argument reference (if it is a reference type) is passed. When you change the argument in the method, the changes (single assignment or compound assignments) is reflected to the copy of the argument/argument reference and it is not reflected to the argument or argument reference itself. This is the default Way in .NET languages (<code>ByVal</code> in Visual Basic.)</li><li>Pass <strong>by reference</strong>. When an argument is passed into a method, either the argument itself (if it is a value type) or the argument reference (if it is a reference type) is directly passed. No other copies are generated. When you change the argument in the method, the changes (single assignment or compound assignments) will reflect to the argument or argument reference itself. This is indicated by using <code>ref</code> keyword in C# or <code>ByRef</code> keyword in Visual Basic.</li></ol><p>For example, the FCL’s Array.Resize() method takes a ref parameter of type Array, this ref value is modified in the method implementation to point to the new space of the array after the resize. You will be able to continue using the variable for that array and access the new space:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">byte</span>[] data = <span style="color: blue">new</span>&nbsp;<span style="color: blue">byte</span>[10];<br><span>Array</span>.Resize(<span style="color: blue">ref</span> data, 20);<br><span>Console</span>.WriteLine(<span>$"New array size is: </span>{data.Length}<span>"</span>);</pre><p>Method can also return a value to the caller, but before C# 7.0, all returns are by value by default.</p><p>With C# 7.0 or later, <strong>ref returns</strong> are supported.</p><h3>Ref Returns</h3><p>Ref Returns are method return values by references. Similar to ref values passed as method arguments, ref returns can be modified by the caller, and any changes (assignments) to the value will reflect to the original value returned from the method. </p><p>In C#, you can make a ref return using the <code>return ref</code> keywords.</p><p>Please see the following example.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">ref</span>&nbsp;<span>T</span> ElementAt&lt;<span>T</span>&gt;(<span style="color: blue">ref</span>&nbsp;<span>T</span>[] array, <span style="color: blue">int</span> position)
{<br>&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (array == <span style="color: blue">null</span>)<br>&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>ArgumentNullException</span>(<span style="color: blue">nameof</span>(array));<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">if</span> (position &lt; 0 || position &gt;= array.Length)<br>&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">throw</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>ArgumentOutOfRangeException</span>(<span style="color: blue">nameof</span>(position));<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span>&nbsp;<span style="color: blue">ref</span> array[position];
}</pre><p>The purpose of the above method is to obtain a reference to the element at the specific position of an array. Later you can use this reference to change the value of the element; because it is a ref value, the changes will apply to the original value in the array.</p><p>To use this method, use ref locals:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">int</span>[] data = <span style="color: blue">new</span>&nbsp;<span style="color: blue">int</span>[10];<br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>$"Before change, element at 2 is: </span>{data[2]}<span>"</span>);<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">ref</span>&nbsp;<span style="color: blue">int</span> value = <span style="color: blue">ref</span> ElementAt(<span style="color: blue">ref</span> data, 2);<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// Change the ref value.<br></span>&nbsp;&nbsp;&nbsp; value = 5;<br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>$"After change, element at 2 is: </span>{data[2]}<span>"</span>);<br>}</pre><p>The Visual Studio IntelliSense will indicate the calling method is a ref return method.</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/12/image188.png"><img width="620" height="212" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/12/image_thumb179.png" border="0"></a></p><p>The output of this code is as below:</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/12/image189.png"><img width="447" height="150" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/12/image_thumb180.png" border="0"></a></p><h3>Call Methods with Ref Returns</h3><p>As previous example, to get a reference of a ref return value, you will need to use ref locals and also put the <code>ref</code> keyword in front of the method (<code>ref</code> in both left and right.)</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">ref</span>&nbsp;<span style="color: blue">int</span> value = <span style="color: blue">ref</span> ElementAt(<span style="color: blue">ref</span> data, 2);
</pre><p>You can also call this method without the <code>ref</code> keyword, making the value returned by value.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">int</span> value = ElementAt(<span style="color: blue">ref</span> data, 2);
</pre><p>In this case, the program output will be as the following:</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/12/image190.png"><img width="445" height="153" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/12/image_thumb181.png" border="0"></a></p><p>However, you need either specify <code>ref</code> in both sides, or not have <code>ref</code> in both sides; you cannot specify <code>ref</code> in one side and not specify <code>ref</code> in the other side.</p><p>Additionally, the following code also works:</p><p><pre style="background: white;color: black;font-family: consolas">ElementAt(<span style="color: blue">ref</span> data, 2) = 5;
</pre><p>You will get the same output as the first example. The element at the position 2 is changed from 0 (default value) to 5. This works because the ref returns can appear as an <strong>LValue</strong>.</p><h3>Overload Resolutions</h3><p>Because return type is not part of method signature to consider an overload, the following method definitions may not work.</p><pre>public int M(int[] value);<br>public ref int M(int[] value);</pre><p>But the following definitions will work, because the parameter is by ref in the first method and is by value in the second method.</p><pre>public ref int M(ref int[] value);<br>public ref int M(int[] value);</pre><p>Therefore, in order to overload a ref return method, you’ll need to satisfy the parameter rules:</p><ul><li>Use different count of parameters, or</li><li>Use different type of parameters, or</li><li>Use different value passing method (by value or by ref) of parameters.</li></ul><h3>Restrictions</h3><p>There are certain restrictions apply.</p><ol><li>The value to be ref returned in a method must be a ref local; the source of this ref local can be an actual <code>ref</code>/<code>out</code> argument of this method, or a field in the type where the method is declared. </li><li>You cannot ref return a <code>void</code> type.</li><li>You cannot ref return a <code>null</code> literal. But you can ref return a ref local whose value is <code>null</code>.</li><li>You cannot ref return from an async method, because the return value might be uncertain by the time the async method returns.</li><li>Constants and enums are not allowed to be ref returned.</li></ol><h3>Conclusion</h3><p>Ref returns is an extension of the C# language, it can improve the performance of the code by reducing the possibility of copying values from method returns. This is useful for those low level programming components such as interoperability, cross-platform, or resource constrained scenarios (Mobile, IoT etc.,) This feature requires no CLR changes because the similar concepts already exist. To use this feature, you will need to use C# language 7.0, by upgrading your Visual Studio version to 2017 or later.</p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 6: Read-only structs</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-6-read-only-structs</link>
      <pubDate>Tue, 21 Nov 2017 23:22:54 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=377</guid>
      <description><![CDATA[C# 7 SeriesPart 1: Value TuplesPart 2: Async MainPart 3: Default LiteralsPart 4: DiscardsPart 5:...]]></description>
      <content:encoded><![CDATA[<p><strong>C# 7 Series</strong></p><p><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/">Part 1: Value Tuples</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main/">Part 2: Async Main</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/06/c-7-series-part-3-default-literals/">Part 3: Default Literals</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/">Part 4: Discards</a><br><a href="https://blogs.msdn.microsoft.com/mazhou/2017/10/05/c-7-series-part-5-private-protected/">Part 5: Private Protected</a><br>Part 6: (This article) Read-only structs</p><h3>Background</h3><p>In .NET world, there are two basic types: <strong>reference types</strong> and <strong>value types</strong>. To be short, Reference types are classes that can be inherited/extended, when passing reference type objects, a “pointer” is passed; value types are structs that cannot be inherited/extended, when passing value type objects, a “copy” is passed. </p><p>A <code>struct</code> in C# is a value type, and it is “internally inherited” from <code>System.ValueType</code>. (I said no inheritance between structs.)<p>When use structs in arguments, a copy of the struct is generated, using structs may be efficient because it reduces the times for heap object allocation. <p>In many scenarios, developers use structs as an efficient way to pass values, such as a return object from a method, or a basic data structure that would be used across the application. <h3>Read-only structs</h3><p>A <code>read-only struct</code> is a <code>struct</code> whose public members are read-only, as well as the “<code>this</code>” parameter.<p>Take a look at the following declaration:<p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">struct</span>&nbsp;<span>S<br></span>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">int</span> Age { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">string</span> Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> S(<span style="color: blue">int</span> age, <span style="color: blue">string</span> name)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.Age = age;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.Name = name;<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> S(<span>S</span> other)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span> = other;<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span>S</span> Replace(<span>S</span> other)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>S</span> value = <span style="color: blue">this</span>;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span> = other;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> value;<br>&nbsp;&nbsp;&nbsp; }<br>}</pre><p>As you can see, I get full access to the declared property <code>Age</code> and <code>Name</code>, I also get access to <code>this</code> parameter so I can replace the instance with another instance of <code>S</code>.<p>If I add the <code>readonly</code> modifier to the declaration, My access will be limited:<ul><li>All members (properties, fields) must be read-only;</li><li>I’ll need to initialize the members in the public parameterized constructor; </li><li>“this” parameter will be read-only in other place except in constructor.</li><li>You cannot define “field-like” events;</li></ul><p>The below screenshot shows what things need to be fixed for the <code>readonly struct</code>. </p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/11/image303.png"><img width="595" height="595" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/11/image_thumb278.png" border="0"></a></p><p>Below is the fixed code:<p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">readonly</span>&nbsp;<span style="color: blue">struct</span>&nbsp;<span>S<br></span>{<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">int</span> Age { <span style="color: blue">get</span>; }<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span>&nbsp;<span style="color: blue">string</span> Name { <span style="color: blue">get</span>; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> S(<span style="color: blue">int</span> age, <span style="color: blue">string</span> name)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.Age = age;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span>.Name = name;<br>&nbsp;&nbsp;&nbsp; }<br><br>&nbsp;&nbsp;&nbsp; <span style="color: blue">public</span> S(<span>S</span> other)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">this</span> = other;<br>&nbsp;&nbsp;&nbsp; }<br>}</pre><p>You can initialize new instances of <code>S</code> as you usually do. But then you cannot modify any members with any instance. You should always call the parameterized (not parameterless) constructor in order to initialize the instance object properly, otherwise you will get a default initialization of the instance (all members are defaulted to initial values of the member type.)<p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">private</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Test()<br>{<br>&nbsp;&nbsp;&nbsp; <span>S</span> s = <span style="color: blue">new</span>&nbsp;<span>S</span>(18, <span>"Anna"</span>);<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">ref</span>&nbsp;<span>S</span> other = <span style="color: blue">ref</span> s;<br>&nbsp;&nbsp;&nbsp; other = <span style="color: blue">new</span>&nbsp;<span>S</span>(other);<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">bool</span> equal = s.Equals(other); <span style="color: green">// true.<br></span>}</pre><h3>Conclusion</h3><p>Read-only structs is a convenient feature that can help to protect your values from unintended modifications outside of your control; in combination with other new features (for example, <code>ref structs</code> and <code>in</code> parameters,) it will make your C# code targeting to low level programming easier. In the next few posts, I will explain all these new things. Please note that you will need C# 7.2 to work with this feature, which is available in <a href="https://www.visualstudio.com/en-us/news/releasenotes/vs2017-Preview-relnotes">Visual Studio 2017.5 Preview 4</a> or later.]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 5: Private Protected</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-5-private-protected</link>
      <pubDate>Thu, 05 Oct 2017 03:34:28 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=355</guid>
      <description><![CDATA[C# has several accessibility modifiers, public, internal, internal protected, and private.Public:...]]></description>
      <content:encoded><![CDATA[<p>C# has several accessibility modifiers, public, internal, internal protected, and private.</p><ul><li><strong>Public</strong>: The member declared with this accessibility can be visible within the assembly containing this member, or any other assembly that references the containing assembly. i.e., access is not limited.</li><li><strong>Internal</strong>: The member declared with this accessibility can be visible within the assembly containing this member, it is not visible to any assembly outside of the containing assembly. i.e., access is limited to containing assembly only.</li><li><strong>Protected</strong>: The member declared with this accessibility can be visible within the types derived from the containing type within the containing assembly, and the types derived from the containing type outside of the containing assembly. i.e., access is limited to derived types of the containing type.</li><li><strong>Internal Protected</strong>: The member declared with this accessibility can be visible within the types derived from the containing type within or outside of the containing assembly, it is also visible to any types within the containing assembly. i.e., access is limited to containing assembly or derived types.</li><li><strong>Private</strong>: The member declared with this accessibility can be visible within the containing type, it is not visible to any derived types, other types in the same assembly or types outside of the containing assembly. i.e., access is limited to the containing type only. </li></ul><h3>Private Protected</h3><p>C# 7.2 is adding a new level of accessibility: private protected. This is to match the same access level that has already been in the CLR.</p><ul><li><strong>Private Protected</strong>: The member declared with this accessibility can be visible within the types derived from this containing type within the containing assembly. It is not visible to any types not derived from the containing type, or outside of the containing assembly. i.e., the access is limited to derived types within the containing assembly.</li></ul><p>This is very helpful if developers want to implement something only visible to internal assembly level. </p><h3>Example</h3><p>To demonstrate the behavior of private protected, I created one solution that contains two projects: one is a Library project, another is a Console App project referencing the Library project. I created types within the Library project:</p><p><pre style="background: white;color: black;font-family: consolas"><p><span style="color: blue">public</span>&nbsp;<span style="color: blue">class</span>&nbsp;<span>Base</span>
{<br>&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">protected</span>&nbsp;<span style="color: blue">private</span>&nbsp;<span style="color: blue">void</span> M()<br>&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>"From Base.M()"</span>);<br>&nbsp;&nbsp;&nbsp;&nbsp; }
}
 
<span style="color: blue">public</span>&nbsp;<span style="color: blue">class</span>&nbsp;<span>D1</span> : <span>Base</span>
{<br>&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">new</span>&nbsp;<span style="color: blue">public</span>&nbsp;<span style="color: blue">void</span> M()<br>&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>"From D1.M()"</span>);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue">base</span>.M();<br>&nbsp;&nbsp;&nbsp;&nbsp; }
}</p></pre><p>In the <font face="Courier New">Base</font> class, I declared a private protected member <font face="Courier New">M()</font>, then in the <font face="Courier New">D1</font> class that is derived from <font face="Courier New">Base</font>, I created a method <font face="Courier New">M()</font> and call <font face="Colonna MT">base.M()</font> internally. These two types are within the same assembly, so I should have access to <font face="Colonna MT">base.M()</font> from <font face="Courier New">D1</font>.</p><p>I then created another class <font face="Courier New">C</font>:</p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">class</span>&nbsp;<span>C<br></span>{<br><span style="color: blue">    public</span>&nbsp;<span style="color: blue">void</span> M()<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>Base</span> b = <span style="color: blue">new</span>&nbsp;<span>Base</span>();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; b.M();<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span>D1</span> d = <span style="color: blue">new</span>&nbsp;<span>D1</span>();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; d.M();<br>&nbsp;&nbsp;&nbsp; }<br>}</pre><p>I was trying to call <font face="Courier New">b.M()</font> in <font face="Courier New">C.M()</font> method, because <font face="Courier New">C</font> is not derived from <font face="Courier New">Base</font>, I don’t have the access to <font face="Courier New">Base.M()</font>, hence the code will not work; I saw this compilation error.</p><p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/10/image155.png"><img width="440" height="244" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/10/image_thumb149.png" border="0"></a></p><p>Lastly, I created a type in the Console App project that is not the containing assembly for <font face="Courier New">Base</font>. If I tried to access <font face="Courier New">Base.M()</font> there, I would be given this compilation error:</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/10/image156.png"><img width="438" height="281" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/10/image_thumb150.png" border="0"></a></p><p>NOTE: To make this work, you will need to upgrade your project to C# 7.2 or latest, </p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/10/image157.png"><img width="606" height="219" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/10/image_thumb151.png" border="0"></a></p><h3>Conclusion</h3><p>Now with C# 7.2, we have five levels of accessibility: public, internal, protected, internal protected, and private protected. The addition of private protected will benefit from limiting the access to only derived types within the containing assembly to have special internal implementation for some members. Read more on this <a href="https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/private-protected.md">Private Protected</a> page for more details.</p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 4: Discards</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-4-discards</link>
      <pubDate>Tue, 27 Jun 2017 03:40:28 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=295</guid>
      <description><![CDATA[Sometimes we want to ignore values returned from a method, especially those out arguments, a typical...]]></description>
      <content:encoded><![CDATA[<p>Sometimes we want to ignore values returned from a method, especially those <font face="Consolas">out</font> arguments, a typical example is to check whether a string can be parsed to another type:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">bool</span> parsedValue;<br><span style="color: blue">if</span> (<span style="color: blue">bool</span>.TryParse(<span>"TRUE"</span>, <span style="color: blue">out</span> parsedValue)) { <span style="color: green">/* Do your stuff */</span> }</pre><p>Here we want to ignore <font face="Consolas">parsedValue</font><font face="Segoe UI">. We also want to make this variable inaccessible so developers cannot reference it.</font></p><p>The C# 7.0 has a new feature called <strong>discards</strong>, which can be used to achieve our goal for this scenario.</p><h2>Discards</h2><p>Discards are local variables which you can assign but cannot read from. i.e. they are “write-only” local variables. They don’t have names, instead, they are represented as a _ (underscore.) _ is a contextual keyword, it is very similar to <font face="Consolas">var</font>, and _ cannot be read (i.e. cannot appear on the right side of an assignment.) </p><p>If we apply the discard to above code, it will look like this:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">if</span> (<span style="color: blue">bool</span>.TryParse(<span>"TRUE"</span>, <span style="color: blue">out</span>&nbsp;<span style="color: blue">bool</span>&nbsp;<span style="color: blue">_</span>)) { <span style="color: green">/* Do your stuff */</span> }
</pre><p>Because _ is unreadable, it will not appear in IntelliSense nor compile the code. </p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/06/image583.png"><img width="278" height="252" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/06/image_thumb556.png" border="0"></a></p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/06/image584.png"><img width="356" height="137" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/06/image_thumb557.png" border="0"></a></p><h2>Places Discards Are Applicable</h2><ul><li>A declaration expression with an <font face="Consolas">out</font> modifier, for example: <font face="Consolas">bool.TryParse(“string”, out _)</font></li><li>Pattern matching clauses, such as <font face="Consolas">case int _</font> or <font face="Consolas">if (x is string _)</font></li><li>Deconstructions:</li><ul><li>In declaration: such as <font face="Consolas">var (a, _, c) = myObj</font></li><li>In assignment: such as <font face="Consolas">var a, b; (a, b) = myObj</font></li><li>Value Tuple deconstructions: such as <font face="Consolas">var (a, _, _) = (1, 2, 3)</font></li></ul></ul><h2>The _ Keyword</h2><p>Please always remember that the _ is a contextual keyword, like <font face="Consolas">var</font>, that means if you have already declared a local variable _ in the current context and it is in scope, the _ will not be a discard and will refer to that local variable in scope.</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/06/image585.png"><img width="464" height="125" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/06/image_thumb558.png" border="0"></a></p><p>More interestingly, look the following code:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">bool</span> _ = <span style="color: blue">false</span>, v = <span style="color: blue">false</span>;<br><span style="color: blue">if</span> (<span style="color: blue">bool</span>.TryParse(<span>"TRUE"</span>, <span style="color: blue">out</span>&nbsp;<span style="color: blue">var</span>&nbsp;<span style="color: blue">_</span>))
{<br>&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">/* Do your stuff */<br></span>&nbsp;&nbsp;&nbsp;&nbsp; v = _;
}</pre><p>What is the value of <font face="Consolas">v</font>? </p><p>The answer is <font face="Consolas">false</font>. The <font face="Consolas">if</font> test is <font face="Consolas">true</font>, and string “TRUE” can parse as a Boolean value <font face="Consolas">true</font><font face="Segoe UI">, but we have <font face="Consolas">out var _</font>, this overrides the scope of the previously declared variable _, and it is a discard. Then the assignment <font face="Consolas">v = _</font> inside <font face="Consolas">if</font> statement just reads the value of previously declared local variable _ (which is <font face="Consolas">false</font>,) and assigns to <font face="Consolas">v</font>, hence the value of v is <font face="Consolas">false</font>. If we remove the <font face="Consolas">var<font face="Segoe UI"> to change the code to </font>out _</font>, the value of <font face="Consolas">v</font> will be <font face="Consolas">true</font> because _ is on longer a discard and it holds the value of the parsed Boolean. </font></p><h2>Conclusion</h2><p>The discards in C# enables a way to ignore some local variables, it is a design time feature, the local variable may still be required at runtime and compiler may also generate a name for it. Since the _ keyword is a contextual keyword, you need to set a code policy to avoid declaring local variables with the name _ to reduce confusions. This feature is compatible with previous versions of .NET platforms as it does not require a CLR change.</p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 3: Default Literals</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-3-default-literals</link>
      <pubDate>Tue, 06 Jun 2017 04:26:20 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=245</guid>
      <description><![CDATA[C#’s default keyword has two kinds of usages: one is to label the fallback branch of the switch…case...]]></description>
      <content:encoded><![CDATA[<p>C#’s <font face="Consolas">default</font> keyword has two kinds of usages: one is to label the fallback branch of the <font face="Consolas">switch…case</font> structure (for any path that does not fall into the <font face="Consolas">case</font> conditions); another is to represent the “default” value of a type. I will discuss this usage in this blog. </p><p>The default value of a type is either:</p><ul><li><font face="Consolas">null</font>, if the type is a reference type, or</li><li>an instance of the type constructed with the parameterless constructor, if the type is a value type. </li></ul><p>The following screenshot is a quick example. </p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/06/image131.png"><img width="416" height="152" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/06/image_thumb130.png" border="0"></a></p><p>However, you can not have a default expression for any open type (Note: An open type is a type that has unbound type arguments; a type has all bound type arguments is called closed type), for example:</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/06/image132.png"><img width="534" height="66" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/06/image_thumb131.png" border="0"></a></p><p>Now, if we want to use default value for a generic type in a method, we have to write code like this:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Method(<span>ImmutableArray</span>&lt;<span style="color: blue">int</span>&gt; array) { }
 
<span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)
{&nbsp;&nbsp;&nbsp;&nbsp; <br>    Method(<span style="color: blue">default</span>(<span>ImmutableArray</span>&lt;<span style="color: blue">int</span>&gt;));
}</pre><p>Do you see a redundant here? the compiler should know the exact type needed for the <strong>Method()</strong> for the first parameter. A <font face="Consolas">default</font> literal without the type specification should be sufficient enough. </p><h2>Default Literals</h2><p>C# 7.1 allows the <font face="Consolas">default</font> expressions. If compile with the C# language version 7.1, or latest, you can simplify the code as the following:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Method(<span>ImmutableArray</span>&lt;<span style="color: blue">int</span>&gt; array) { }<br><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{ <br>    Method(<span style="color: blue">default</span>);<br>}</pre><p>Now you get a clean code!</p><p>Similarly, you can have default literals for all the place that <font face="Consolas">default(…)</font> can appear:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args = <span style="color: blue">default</span>)&nbsp;&nbsp;&nbsp; <span style="color: green">// Default value for the optional parameter</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br><span style="color: blue">    int</span> i = <span style="color: blue">default</span>;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Default value (0) for type System.Int32</span>&nbsp;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">string</span> s = <span style="color: blue">default</span>;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Default value (null) for type System.String</span>&nbsp;<br>&nbsp;&nbsp;&nbsp; Method(<span style="color: blue">default</span>);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Calling a method with default value for an argument</span>&nbsp;<br>&nbsp;&nbsp;&nbsp; T t = <span style="color: blue">default</span>;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Default value for a type parameter</span>&nbsp;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span>&nbsp;<span style="color: blue">default</span>;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Default return value for a method that does not return void</span>&nbsp;<br>}</pre><p>You can have default literals in a condition test:</p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">int</span> x = 2; <br><span style="color: blue">if</span> (x == <span style="color: blue">default</span>) { }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Test if x is default value (0) of the type System.Int32</span>&nbsp;<br><span style="color: blue">if</span> (x <span style="color: blue">is</span>&nbsp;<span style="color: blue">default</span>) { }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: green">// Same as above</span></pre><p>More interestingly, you can use default literals in <font face="Consolas">switch…case</font>. Oh, cool! but… wait, how about the label ‘<font face="Consolas">case default</font>’? Here is what I get from the IDE:</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/06/image133.png"><img width="758" height="168" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/06/image_thumb132.png" border="0"></a></p><p>And if you apply the fix, it will be:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">int</span> x = 2; <br><span style="color: blue">switch</span> (x) <br>{ <br>&nbsp;&nbsp;&nbsp; <span style="color: blue">case</span> (<span style="color: blue">default</span>): <span style="color: blue">break</span>; <br>&nbsp;&nbsp;&nbsp; <span style="color: blue">default</span>: <span style="color: blue">break</span>; <br>}</pre><p>This looks confusing, but at least we get live analytics about this, Thanks Roslyn! </p><p>The last thing I want to call out is there are cases that cannot apply default literals, for example: </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: green">// Error: 'as' must have reference type <br></span><span style="color: blue">default</span>&nbsp;<span style="color: blue">as</span>&nbsp;<span style="color: blue">int</span>; <br><span style="color: green">// OK. But the left hand expression is always null.</span>
<span style="color: blue">if</span> (<span style="color: blue">default</span>&nbsp;<span style="color: blue">as</span>&nbsp;<span style="color: blue">string</span> == <span style="color: blue">string</span>.Empty) { }
<span style="color: green">// Error. Cannot apply operator 'is' to type 'default'.</span>
<span style="color: blue">if</span> (<span style="color: blue">default</span>&nbsp;<span style="color: blue">is</span>&nbsp;<span style="color: blue">string</span>) { }</pre><h2>Conclusion</h2><p>Default literals in C# 7.1 avoids redundant typing where the default value is known to compiler. This is a syntactical improvement and nothing changed for the CLR, The new code is 100% compatible with the code built by earlier versions of the C# compiler. </p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 2: Async Main</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-2-async-main</link>
      <pubDate>Tue, 30 May 2017 02:53:12 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=175</guid>
      <description><![CDATA[As you may know, there are two kinds of the programs the C# language can build. One is a program...]]></description>
      <content:encoded><![CDATA[<p>As you may know, there are two kinds of the programs the C# language can build. One is a program with an entrypoint so that the Operating System can load the program and execute it from the entrypoint; another is the program without an entrypoint. Operating System cannot directly execute the program, the program can be referenced by other program with an entrypoint, and the code can be then executed. </p><p>Application types that (must) have an entrypoint: Windows Forms App, UWP App, Console App, WPF App, ASP.NET and ASP.NET Core App and Xamarian App.</p><p>Application types that do not need an entrypoint: Class Library (/t:lib), Modules (/t:module).</p><h2>The Main Method</h2><p>Like other languages, C# program starts with the <strong>Main</strong> method. There are four overloads that are considered as the valid signatures for the <strong>Main</strong> method.</p><pre>public static void Main();
public static int Main();
public static void Main(string[] args);
public static int Main(string[] args);</pre><p>The C# entrypoint method must be <font face="Consolas">static</font>, name of the method must be <font face="Consolas">Main</font>, return type of this method can be either <font face="Consolas">void</font> or <font face="Consolas">int</font>, it can have one parameter of a <font face="Consolas">string</font> array, containing any command-line arguments. </p><p>If the entrypoint returns an <font face="Consolas">int</font>, then the value can be evaluated by the Operating System, or the host process that started the program with this entrypoint, this is widely used in the native world (such as to indicate successful launch of an external app.)</p><h2>The Async Main Method</h2><p>C# introduced async/await pattern in version 5.0 (with .NET Framework 4.5), allowing easy-to-read workflow for an asynchronous operation. Many existing language constructs for those async operations (aka. async programming models) can work with the new <font face="Consolas">async</font>/<font face="Consolas">await</font> keywords. Today, community develops many libraries that only provide async version of the operations. (for example, <strong>System.Net.HttpClient</strong>, <strong>Microsoft.Azure.EventHub.Core.</strong>)</p><p>As I showed above, if you want to await an async operation in the entrypoint method, you need to apply some workaround, because the following entrypoint definition is invalid:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">async</span>&nbsp;<span>Task</span> Main(<span style="color: blue">string</span>[] args) <br>{ <br>&nbsp;&nbsp;&nbsp; <span style="color: blue">await</span> BuildWebHost(args).RunAsync(); <br>}</pre><p><a href="https://msdnshared.blob.core.windows.net/media/2017/05/image664.png"><img width="591" height="31" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/05/image_thumb536.png" border="0"></a></p><p>The workaround would be synchronously wait for the operation.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)
{&nbsp;&nbsp;&nbsp;&nbsp; <br>    BuildWebHost(args).RunAsync().GetAwaiter().GetResult();
}</pre><p>Or calling Wait() on the Task object:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">static</span>&nbsp;<span style="color: blue">void</span> Main(<span style="color: blue">string</span>[] args)<br>{
    BuildWebHost(args).RunAsync().Wait();
}</pre><p>In C# 7.1, the language extends the valid signatures of an entrypoint to allow these async overloads of the Main method to be valid. </p><pre><p>public static void Main();
public static int Main();
public static void Main(string[] args);
public static int Main(string[] args);<br>public static Task Main();<br>public static Task&lt;int&gt; Main();<br>public static Task Main(string[] args);<br>public static Task&lt;int&gt; Main(string[] args);</p></pre><p>A Task-like return type enables the <font face="Consolas">await</font> keyword with the <font face="Consolas">async</font> modifier in the entrypoint method. </p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/05/image665.png"><img width="607" height="489" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/05/image_thumb537.png" border="0"></a></p><h2>Conclusion</h2><p>The Async Main makes the asynchronous operations in the entrypoint method easier to use, without any workaround, like it runs in other async methods. In the compiler time, Any async Main method will be wrapped as a non-async Main method that can be accepted by the CLR Host. Since this feature does not correspond to a CLR code change, the async Main method is just a syntactical sugar. This design allows backend compatibility with the previous versions of the language. To read more details, please see <a href="https://github.com/dotnet/csharplang/blob/master/proposals/async-main.md">Async Main</a> in the Roslyn Git repo. </p>]]></content:encoded>
    </item>
    <item>
      <title>C# 7 Series, Part 1: Value Tuples</title>
      <link>https://docs.microsoft.com/archive/blogs/mazhou/c-7-series-part-1-value-tuples</link>
      <pubDate>Fri, 26 May 2017 04:56:08 GMT</pubDate>
      <dc:creator><![CDATA[mazhou]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/mazhou/?p=135</guid>
      <description><![CDATA[Starting today I will start a new C# 7 series, to introduce new language features of C# 7+ features....]]></description>
      <content:encoded><![CDATA[<p>Starting today I will start a new C# 7 series, to introduce new language features of C# 7+ features. Please note that I am not saying C# 7.0, I am saying C# 7 plus, because there will be minor language versions (like 7.1, 7.2) that will bring <a href="https://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md">new features</a> in steps (thanks to Roslyn!) such as async Main and default literals. </p><h2>Tuples</h2><p>The <a href="https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx">System.Tuple</a> class provides a type to represent a key-value like property bag. It can be used where you want to have a data structure to hold an object with properties (elements) but you don’t want to create a separate type for it. The following code shows how you use it as a return value of a method that holds the name and the age of a student. </p><p><pre style="background: white;color: black;font-family: consolas"><p><span style="color: blue">public</span>&nbsp;<span>Tuple</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt; GetStudentInfo(<span style="color: blue">string</span> id)
{&nbsp;&nbsp;&nbsp;&nbsp; <br>    <span style="color: green">// Search by ID and find the student.<br></span>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span>&nbsp;<span style="color: blue">new</span>&nbsp;<span>Tuple</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;(<span>"Annie"</span>, 25);
}</p></pre><p>As you can see, I am returning an instance of Tuple&lt;string, int&gt; object with first argument is the name and the second argument is the age. Later on we can have code to call this method, like this:</p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span>&nbsp;<span style="color: blue">void</span> Test()
{&nbsp;&nbsp;&nbsp;&nbsp; <br>    <span>Tuple</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt; info = GetStudentInfo(<span>"100-000-1000"</span>);<br>    <span>Console</span>.WriteLine(<span>$"Name: </span>{info.Item1}<span>, Age: </span>{info.Item2}<span>"</span>);
}</pre><p>You can access <em>name</em> and <em>age</em> by referencing <strong>Item1</strong> and <strong>Item2</strong>. </p><p>The <strong>Tuple</strong> class has some obvious problems:</p><ul><li>You need to access the properties with a name pattern <em>ItemX</em>, the property name may not make sense to the caller, that would be better if we can write something like <em>info.Name</em> and i<em>nfo.Age</em> instead of <em>info.;Item1</em> and <em>info.Item2</em>.</li><li>You are limited to have maximum 8 properties. If you want more, the last type argument must be another <em>Tuple</em>. This makes the syntax super hard to understand.</li><li><strong>Tuple</strong> is a reference type, not like other primitive types (they are most value types), it allocates on heap and it could be too much object creation/allocation for CPU intensive operations.</li></ul><h2>Value Tuples</h2><p>C# 7.0 introduced <a href="https://msdn.microsoft.com/en-us/library/system.valuetuple(v=vs.110).aspx">ValueTuple</a> structure, which is a value type representation of the tuple object. The language team made many good things for this value tuple type, including a new syntax and many features (such as deconstruction.)</p><p>The following is a rewrite version with the value tuples, Note that if you don’t see the <strong>ValueTuple</strong> available in your project, you have to download the System.ValueTuple 4.3.0 NuGet package to your project. You don’t need to do anything if you are using .NET Framework 4.7 or higher, or .NET Standard Library 2.0 or higher. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span> (<span style="color: blue">string</span>, <span style="color: blue">int</span>) GetStudentInfo(<span style="color: blue">string</span> id)
{<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// Search by ID and find the student.</span>&nbsp;<br>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> (<span>"Annie"</span>, 25);
}
 
<span style="color: blue">public</span>&nbsp;<span style="color: blue">void</span> Test()
{ <br>&nbsp;&nbsp;&nbsp; (<span style="color: blue">string</span>, <span style="color: blue">int</span>) info = GetStudentInfo(<span>"100-000-1000"</span>); <br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>$"Name: </span>{info.Item1}<span>, Age: </span>{info.Item2}<span>"</span>);
}</pre><p>The code above is much simplified by using the first-class syntax ().</p><p>You can even give a name to every element in the value tuple, like this:</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">public</span> (<span style="color: blue">string</span> name, <span style="color: blue">int</span> age) GetStudentInfo(<span style="color: blue">string</span> id)
{<br>&nbsp;&nbsp;&nbsp; <span style="color: green">// Search by ID and find the student.<br></span>&nbsp;&nbsp;&nbsp; <span style="color: blue">return</span> (name: <span>"Annie"</span>, age: 25);
}
 
<span style="color: blue">public</span>&nbsp;<span style="color: blue">void</span> Test()
{<br>&nbsp;&nbsp;&nbsp; (<span style="color: blue">string</span> name, <span style="color: blue">int</span> age) info = GetStudentInfo(<span>"100-000-1000"</span>); <br>&nbsp;&nbsp;&nbsp; <span>Console</span>.WriteLine(<span>$"Name: </span>{info.name}<span>, Age: </span>{info.age}<span>"</span>);
}</pre><p>Perfect! Now you have good metadata for the elements in tuple objects, you then don’t need to go back and forth to make sure you are returning/accessing elements in the right order as its original definition. </p><p>The Visual Studio IDE will give you hints when you work with the value tuples.</p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/05/image487.png"><img width="377" height="107" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/05/image_thumb446.png" border="0"></a></p><p><a href="https://msdnshared.blob.core.windows.net/media/2017/05/image488.png"><img width="568" height="331" title="image" alt="image" src="https://msdnshared.blob.core.windows.net/media/2017/05/image_thumb447.png" border="0"></a></p><h2>Value Tuple Deconstruction</h2><p>You can deconstruct the elements from the value tuple object, and access the local variables. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: green">// Deconstruct using the var (x, y) syntax,<br></span><span style="color: green">// or (var x, var y) syntax.<br></span><span style="color: blue">var</span> (name, age) = GetStudentInfo(<span>"100-000-1000"</span>);<br><span style="color: green">// Now you have two local variables: name and age.<br></span><span>Console</span>.WriteLine(<span>$"Name: </span>{name}<span>, Age: </span>{age}<span>"</span>);</pre><p>If you just care about certain elements but not all, you can use the _ keyword to ignore the local variable. </p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: green">// Deconstruct using the var (x, y) syntax,<br></span><span style="color: green">// or (var x, var y) syntax.<br></span><span style="color: blue">var</span> (name, <span style="color: blue">_</span>) = GetStudentInfo(<span>"100-000-1000"</span>);<br><span style="color: green">// Now you have just one local variable: name. The value for age is ignored.<br></span><span>Console</span>.WriteLine(<span>$"Name: </span>{name}<span>"</span>);</pre><h2>Value Tuples to Tuples</h2><p>The <strong>System.Tuple</strong> and <strong>System.ValueTuple</strong> provides some extension methods to help convert between <strong>Tuple</strong> and <strong>ValueTuple</strong>.</p><p><pre style="background: white;color: black;font-family: consolas"><span style="color: blue">var</span> valueTuple = (id: 1, name: <span>"Annie"</span>, age: 25, dob: <span>DateTime</span>.Parse(<span>"1/1/1993"</span>));<br><span style="color: blue">var</span> tuple = valueTuple.ToTuple();</pre><h2>Conclusion</h2><p><strong>ValueTuple</strong> makes the C# language more modern, and easy to use with simplified syntax. It solves many <strong>Tuple</strong> problems:</p><ul><li>Value Tuple objects have first class syntax support, it simplifies the code to work with tuple elements. </li><li>You can associate a name with the value tuple element, you get some level of design time and compiler time validation of your code.</li><ul><li>Please <font>NOTE</font> that the <font>name associated with the tuple element is not a runtime metadata</font>, i.e. there is no such a property/field with the name on the actual instance of that value tuple object, the property names are still Item1, Item2, etc., all element names are design time and compiler time only.</li></ul><li>You are now flexible to access all tuple elements, or some of them, by using the deconstruction and the _ keyword.</li><li>Value Tuple types are value types, no inheritance or other features, this means that the value tuples are better performance. </li></ul><p>Since the name of the value tuple element is not runtime, you have to be careful using it when doing serialization with existing libraries, such as Newtonsoft.Json, Unless the library updated to support the new metadata (<strong>TupleElementNameAttribute</strong> etc.) before then you would run into bugs. </p>]]></content:encoded>
    </item>
  </channel>
</rss>