<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.NET Archives - CodeJourney.net</title>
	<atom:link href="https://www.codejourney.net/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codejourney.net/tag/net/</link>
	<description>Pragmatic full stack software development</description>
	<lastBuildDate>Tue, 03 Dec 2024 18:30:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/cropped-512px-na-512px-JPEG-BEZ-NAPISU-1.jpg?fit=32%2C32&#038;ssl=1</url>
	<title>.NET Archives - CodeJourney.net</title>
	<link>https://www.codejourney.net/tag/net/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">123174533</site>	<item>
		<title>Real .NET Interview Questions (2024/2025)</title>
		<link>https://www.codejourney.net/real-net-interview-questions-2024-2025/</link>
					<comments>https://www.codejourney.net/real-net-interview-questions-2024-2025/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 03 Dec 2024 16:16:31 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4909</guid>

					<description><![CDATA[<p>From September to November 2024 I had a &#8220;pleasure&#8221; of looking for a new programming job as a senior full stack .NET developer. I was dedicated full time to this process as I have still been on a sabbatical break. It took me a bit more than 2 months, during which I submitted around 150&#8230;</p>
<p>The post <a href="https://www.codejourney.net/real-net-interview-questions-2024-2025/">Real .NET Interview Questions (2024/2025)</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>From September to November 2024 I had a &#8220;pleasure&#8221; of looking for a new programming job as a senior full stack .NET developer. I was dedicated full time to this process as <a href="https://www.codejourney.net/what-im-doing-with-two-months-of-full-time-coding-for-fun/">I have still been on a sabbatical break</a>. It took me a bit more than 2 months, during which I submitted around 150 well-crafted applications, took part in 25 full technical recruitment processes and was asked hundreds of .NET interview questions.</p>



<p>In this article, I&#8217;m sharing a compiled list of the most popular .NET interview questions I was asked during all those interviews. They represent real questions asked on job interviews for a software developer with almost 10 years of experience. Hope you enjoy it <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<span id="more-4909"></span>



<h2 class="wp-block-heading">Technical .NET Interview Questions</h2>



<ol class="wp-block-list">
<li>What&#8217;s the difference between a <code>class</code> and an <code>interface</code>?</li>



<li>What&#8217;s the difference between an <code>abstract class</code> and an <code>interface</code>?</li>



<li>What is the difference between a <code>class</code> and a <code>struct</code>?</li>



<li>Describe the difference between overriding and overloading in C#</li>



<li>Can a <code>structure</code> have <code>virtual</code> methods?</li>



<li>Explain the difference between <code>GET</code>, <code>POST</code> and <code>PATCH</code> in HTTP APIs</li>



<li>Is there any limit go the <code>GET</code> request&#8217;s length? If yes, where is such a limit configured? What about <code>POST</code>?</li>



<li>How would you secure your WebAPI?</li>



<li>What is the flow of generating, obtaining and passing JWT token in a .NET application?</li>



<li>When using JWT tokens in an API, how does the server ensure it talks to a legitimate client?</li>



<li>Is the API security compromised when the user&#8217;s JWT token is stolen?</li>



<li>What is the difference between <code>IEnumerable</code> and <code>IQueryable</code> in the context of Entity Framework?</li>



<li>What are the dependency injection scopes in ASP.NET?</li>



<li>How can dependency injection be helpful in testing?</li>



<li>What is <code>IHttpClientFactory</code> used for and which issues does it help to eliminate?</li>



<li>What is wrong with creating <code>HttpClient</code> manually?</li>



<li>What would you choose for implementing communication between microservices: REST or a message broker? What would you consider when making such a choice?</li>



<li>What would you do as a backend developer when frontend developers are blocked because they are missing an API endpoint from your side?</li>



<li>What is the size of stack in .NET?</li>



<li>What are value and reference types? What is the difference between them? Give a practical example</li>



<li>Which objects go on Large Object Heap?</li>



<li>What is JIT compilation?</li>



<li>Describe the strategies for delivering a message in a message queue</li>



<li>When is <code>Dispose</code> method called on a class implementing <code>IDisposable</code>?</li>



<li>What is the difference between <code>Dispose</code> and <code>Finalize</code>?</li>



<li>What is SOLID? Can you elaborate on each SOLID acronym?</li>



<li>You are assigned a task to process a large piece of text by inserting and changing many parts of it. Which of the following would you use for that task: <code>string</code>, <code>StringBuilder</code>, <code>StringWriter</code> or <code>StringReader</code>?</li>



<li>What&#8217;s the difference between Repository and Query Object patterns?</li>



<li>What is the Saga pattern?</li>



<li>What is CQRS and in which scenarios may it be beneficial?</li>



<li>What is the difference between an event and a command (like in CQRS)?</li>



<li>What are the advantages and disadvantages of using a Repository pattern?</li>



<li>What is Clean Architecture? Who invented it and how it works?</li>



<li>What is Onion Architecture?</li>



<li>What is Modular Monolith?</li>
</ol>



<h2 class="wp-block-heading">Experience-related .NET Interview Questions</h2>



<ol start="36" class="wp-block-list">
<li>Describe how you realized authentication &amp; authorization in your last project</li>



<li>Explain your last project’s architecture</li>



<li>Explain a challenging task you faced in your last project and how you solved it</li>



<li>How would you approach diagnosing a performance issue on production, which cannot be reproduced locally?</li>



<li>Explain the &#8220;event-based architecture&#8221; you implemented in your last project. This was something I explicitly mentioned in my resume, so the advice is: prepare to elaborate on every experience you mention in your resume <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>



<li>How would you choose tech stack for a new full stack web application (backend + frontend)? Describe your decision-making process: what would you take into consideration when choosing a tech stack?</li>



<li>How would you decide whether to use an already-existing component (e.g. a library) vs implementing your own?</li>
</ol>



<h2 class="wp-block-heading">Final tips</h2>



<p>These were not all of the questions I was asked, but the ones that recurred most frequently. As a programmer with almost 10 years of professional experience, I wasn&#8217;t asked many basic programming questions. The recruiters were mostly focused on my experience. They wanted to know how I solved problems at work in the past and what&#8217;s my approach to tackling issues. Rather than asking me theories about a design pattern, they wanted to know how I applied it in practice and whether I was happy with deciding to use it in the first place.</p>



<p>My general advice is to be patient and iterate. After each technical interview, try to write down as many questions as you can remember. This will help you be better and better prepared with each interview you take. Don&#8217;t forget to update your <a href="https://www.linkedin.com/in/dawidsibinski/">LinkedIn profile</a> and keep building a quality network, even if you&#8217;re not on the job lookout right now. It comes in handy!</p>



<p>If you happen to be in a work search right now, I keep my fingers crossed! I hope these .NET interview questions will help you get that dream job <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>If you&#8217;re interested in knowing something about programming job search in current market conditions, feel free to leave a comment <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/real-net-interview-questions-2024-2025/">Real .NET Interview Questions (2024/2025)</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/real-net-interview-questions-2024-2025/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4909</post-id>	</item>
		<item>
		<title>Typing API Responses With Zod</title>
		<link>https://www.codejourney.net/typing-api-responses-with-zod/</link>
					<comments>https://www.codejourney.net/typing-api-responses-with-zod/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 11 Jul 2022 07:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[zod]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4093</guid>

					<description><![CDATA[<p>Have you ever needed to synchronize types in your frontend app with the backend API? If you ever had an API action defined like that in your controller: and fetched this data using TypeScript in the following way: at some point, you probably also experienced the desynchronization of backend (C#, in our example) and frontend&#8230;</p>
<p>The post <a href="https://www.codejourney.net/typing-api-responses-with-zod/">Typing API Responses With Zod</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Have you ever needed to synchronize types in your frontend app with the backend API?</p>



<p>If you ever had an API action defined like that in your controller:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117275988" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-aspnetcontrollersample-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="AspNetControllerSample.cs content, created by dsibinski on 02:22PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="AspNetControllerSample.cs">
        <tr>
          <td id="file-aspnetcontrollersample-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-aspnetcontrollersample-cs-LC1" class="blob-code blob-code-inner js-file-line">public record UserViewModel(Guid Id, string Name, string LastName, string Login, </td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-aspnetcontrollersample-cs-LC2" class="blob-code blob-code-inner js-file-line">    bool IsActive, int LoyaltyPoints, AddressViewModel? Address = null);</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-aspnetcontrollersample-cs-LC3" class="blob-code blob-code-inner js-file-line">    </td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-aspnetcontrollersample-cs-LC4" class="blob-code blob-code-inner js-file-line">// &#8230;</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-aspnetcontrollersample-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-aspnetcontrollersample-cs-LC6" class="blob-code blob-code-inner js-file-line">public List&lt;UserViewModel&gt; AllUsers()</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-aspnetcontrollersample-cs-LC7" class="blob-code blob-code-inner js-file-line">{</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-aspnetcontrollersample-cs-LC8" class="blob-code blob-code-inner js-file-line">    var usersViewModels = TestDataGenerator.GetTestUsers();</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-aspnetcontrollersample-cs-LC9" class="blob-code blob-code-inner js-file-line">    return usersViewModels.OrderBy(uvm =&gt; uvm.Name).ToList();</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrollersample-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-aspnetcontrollersample-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/bf658760106de7269ebf3d0f351c0411/raw/2336445c10cd9b76b7a5b9af3a747eeaddfb75c4/AspNetControllerSample.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/bf658760106de7269ebf3d0f351c0411#file-aspnetcontrollersample-cs" class="Link--inTextBlock">
          AspNetControllerSample.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>and fetched this data using TypeScript in the following way:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276011" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-apifetchsample-ts" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-typescript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="ApiFetchSample.ts content, created by dsibinski on 02:23PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="ApiFetchSample.ts">
        <tr>
          <td id="file-apifetchsample-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-apifetchsample-ts-LC1" class="blob-code blob-code-inner js-file-line">getAllUsers = async (): Promise&lt;UserViewModel[]&gt; =&gt; {</td>
        </tr>
        <tr>
          <td id="file-apifetchsample-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-apifetchsample-ts-LC2" class="blob-code blob-code-inner js-file-line">    const url = `${this.apiEndpoint}/AllUsers`;</td>
        </tr>
        <tr>
          <td id="file-apifetchsample-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-apifetchsample-ts-LC3" class="blob-code blob-code-inner js-file-line">    const response = await fetch(url);</td>
        </tr>
        <tr>
          <td id="file-apifetchsample-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-apifetchsample-ts-LC4" class="blob-code blob-code-inner js-file-line">    const users = (await response.json()) as UserViewModel[];</td>
        </tr>
        <tr>
          <td id="file-apifetchsample-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-apifetchsample-ts-LC5" class="blob-code blob-code-inner js-file-line">    return users;</td>
        </tr>
        <tr>
          <td id="file-apifetchsample-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-apifetchsample-ts-LC6" class="blob-code blob-code-inner js-file-line">  };</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/44438baa3b6ece08a191b0e918c01a77/raw/5eb52ec2972eae06d298fd6fecca1aadb568ac13/ApiFetchSample.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/44438baa3b6ece08a191b0e918c01a77#file-apifetchsample-ts" class="Link--inTextBlock">
          ApiFetchSample.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>at some point, you probably also experienced the desynchronization of backend (C#, in our example) and frontend (TypeScript) types definitions. What if someone has changed the C# version of <code>UserViewModel</code>, but no one corrected its TypeScript&#8217;s equivalent? </p>



<p>Your TypeScript fetching code will tell nothing about that. <strong>There will be no error, even though the fetched data doesn&#8217;t match the expected <code>UserViewModel</code> type</strong>.</p>



<p>I&#8217;ll try to address this issue in this article <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Let&#8217;s see how typing API responses with <code>zod</code> can help us here.</p>



<span id="more-4093"></span>



<h2 class="wp-block-heading">Synchronization of Backend and Frontend API Typings</h2>



<p>First, why would we want to keep the backend and frontend models in sync?</p>



<p>For me, that&#8217;s the purpose of using TypeScript. <strong>We want our code to be as well-typed as possible</strong>. For instance, we normally want the data displayed to the user to be fully typed. TypeScript enhances our programming experience by providing us with typing information. Thanks to that, we know <em>what is what</em> and <em>what contains</em> <em>what</em>. We also express what types of data we expect in particular cases.</p>



<p>The APIs mostly return JSON data, which can be anything. Because of that, it is much easier to have the data returned from the API fully typed in TypeScript. Thanks to that, <strong>we know what properties are available on the data models received from the API and whether we can use and display them to the users</strong>.</p>



<p>The sample code used within this article is available <a href="https://github.com/dsibinski/DotNetReactZodApp">on GitHub</a>. We will use ASP.NET Core (C#) and React (TypeScript) apps as examples.</p>



<h3 class="wp-block-heading">Models synchronization example</h3>



<p>As we saw in the beginning, a classic example is an API controller that returns a strongly-typed data:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276293" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-aspnetcontrolleraction-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="AspNetControllerAction.cs content, created by dsibinski on 02:57PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="AspNetControllerAction.cs">
        <tr>
          <td id="file-aspnetcontrolleraction-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-aspnetcontrolleraction-cs-LC1" class="blob-code blob-code-inner js-file-line">public List&lt;UserViewModel&gt; AllUsers()</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrolleraction-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-aspnetcontrolleraction-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrolleraction-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-aspnetcontrolleraction-cs-LC3" class="blob-code blob-code-inner js-file-line">    var usersViewModels = TestDataGenerator.GetTestUsers();</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrolleraction-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-aspnetcontrolleraction-cs-LC4" class="blob-code blob-code-inner js-file-line">    return usersViewModels.OrderBy(uvm =&gt; uvm.Name).ToList();</td>
        </tr>
        <tr>
          <td id="file-aspnetcontrolleraction-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-aspnetcontrolleraction-cs-LC5" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/237ce046ebdfcae6b4b7485f8c8c2006/raw/f71478548ff7ccf10fe92893a8c1aedf3ead32e3/AspNetControllerAction.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/237ce046ebdfcae6b4b7485f8c8c2006#file-aspnetcontrolleraction-cs" class="Link--inTextBlock">
          AspNetControllerAction.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>The returned data type is a collection of <code>UserViewModel</code> objects. Here&#8217;s the C# definition of this type:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276303" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-userviewmodel-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="UserViewModel.cs content, created by dsibinski on 02:58PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="UserViewModel.cs">
        <tr>
          <td id="file-userviewmodel-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-userviewmodel-cs-LC1" class="blob-code blob-code-inner js-file-line">public record UserViewModel(Guid Id, string Name, string LastName, </td>
        </tr>
        <tr>
          <td id="file-userviewmodel-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-userviewmodel-cs-LC2" class="blob-code blob-code-inner js-file-line">    string Login, bool IsActive, int LoyaltyPoints, AddressViewModel? Address = null);</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/a6921cad261fb274900c991956a18f5a/raw/646dc5ed47ba33b0d663d20716697c1da6933fd3/UserViewModel.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/a6921cad261fb274900c991956a18f5a#file-userviewmodel-cs" class="Link--inTextBlock">
          UserViewModel.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Its equivalent is also defined on TypeScript side:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276311" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-userviewmodel-ts" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-typescript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="userViewModel.ts content, created by dsibinski on 02:59PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="userViewModel.ts">
        <tr>
          <td id="file-userviewmodel-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-userviewmodel-ts-LC1" class="blob-code blob-code-inner js-file-line">export interface UserViewModel {</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-userviewmodel-ts-LC2" class="blob-code blob-code-inner js-file-line">  id: Guid;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-userviewmodel-ts-LC3" class="blob-code blob-code-inner js-file-line">  name: string;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-userviewmodel-ts-LC4" class="blob-code blob-code-inner js-file-line">  lastName: string;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-userviewmodel-ts-LC5" class="blob-code blob-code-inner js-file-line">  login: string;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-userviewmodel-ts-LC6" class="blob-code blob-code-inner js-file-line">  isActive: boolean;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-userviewmodel-ts-LC7" class="blob-code blob-code-inner js-file-line">  loyaltyPoints: number;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-userviewmodel-ts-LC8" class="blob-code blob-code-inner js-file-line">  address: AddressViewModel | null;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-userviewmodel-ts-LC9" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/d03ea25ba0be55e645a0b6fe35595f47/raw/5d93472032cf0339bc34e88bb76c6be66f17241c/userViewModel.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/d03ea25ba0be55e645a0b6fe35595f47#file-userviewmodel-ts" class="Link--inTextBlock">
          userViewModel.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<h3 class="wp-block-heading">Usage in TypeScript</h3>



<p>Cool. With this simple code, we can create a <code>usersService.ts</code> file and fetch our users&#8217; data from the API. Notice how we make this call strongly typed:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276316" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-usersservice-ts" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-typescript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="usersService.ts content, created by dsibinski on 03:00PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="usersService.ts">
        <tr>
          <td id="file-usersservice-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-usersservice-ts-LC1" class="blob-code blob-code-inner js-file-line">export class UsersService {</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-usersservice-ts-LC2" class="blob-code blob-code-inner js-file-line">  private apiEndpoint: string;</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-usersservice-ts-LC3" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-usersservice-ts-LC4" class="blob-code blob-code-inner js-file-line">  constructor() {</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-usersservice-ts-LC5" class="blob-code blob-code-inner js-file-line">    this.apiEndpoint = &quot;https://localhost:7131/Users&quot;;</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-usersservice-ts-LC6" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-usersservice-ts-LC7" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-usersservice-ts-LC8" class="blob-code blob-code-inner js-file-line">  getAllUsers = async (): Promise&lt;UserViewModel[]&gt; =&gt; {</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-usersservice-ts-LC9" class="blob-code blob-code-inner js-file-line">    const url = `${this.apiEndpoint}/AllUsers`;</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-usersservice-ts-LC10" class="blob-code blob-code-inner js-file-line">    const response = await fetch(url);</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-usersservice-ts-LC11" class="blob-code blob-code-inner js-file-line">    const users = (await response.json()) as UserViewModel[];</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-usersservice-ts-LC12" class="blob-code blob-code-inner js-file-line">    return users;</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-usersservice-ts-LC13" class="blob-code blob-code-inner js-file-line">  };</td>
        </tr>
        <tr>
          <td id="file-usersservice-ts-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-usersservice-ts-LC14" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/b49678cb4bb3d9ed23b9e59ecd58b595/raw/7cd1a292499e4610a6f85f20678496f1592192b8/usersService.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/b49678cb4bb3d9ed23b9e59ecd58b595#file-usersservice-ts" class="Link--inTextBlock">
          usersService.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Everything looks legit. We can use the data retrieved from the API in <code>UsersList</code> component and everything is nicely typed:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="736" height="403" data-attachment-id="4108" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/1_userslisttyped/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/1_UsersListTyped.png?fit=736%2C403&amp;ssl=1" data-orig-size="736,403" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="1_UsersListTyped" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/1_UsersListTyped.png?fit=736%2C403&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/1_UsersListTyped.png?resize=736%2C403&#038;ssl=1" alt="UsersList React component" class="wp-image-4108" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/1_UsersListTyped.png?w=736&amp;ssl=1 736w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/1_UsersListTyped.png?resize=300%2C164&amp;ssl=1 300w" sizes="(max-width: 736px) 100vw, 736px" /></figure>
</div>


<p>The data is even perfectly displayed:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" decoding="async" width="950" height="381" data-attachment-id="4109" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/2_usersdatadispayed/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?fit=950%2C381&amp;ssl=1" data-orig-size="950,381" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="2_UsersDataDispayed" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?fit=950%2C381&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?resize=950%2C381&#038;ssl=1" alt="Table with users rendered on the web page" class="wp-image-4109" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?w=950&amp;ssl=1 950w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?resize=300%2C120&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?resize=768%2C308&amp;ssl=1 768w" sizes="(max-width: 950px) 100vw, 950px" /></figure>
</div>


<p>So, what can go wrong here? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">The Problem &#8211; Typings&#8217; Desynchronization</h2>



<p>Let&#8217;s say that a backend developer implements a requirement to rename &#8220;loyalty points&#8221; into &#8220;fidelity points&#8221;. Easy. (S)he renames <code>LoyaltyPoints</code> property in the C#&#8217;s <code>UserViewModel</code> to <code>FidelityPoints</code>.</p>



<p>The new C# model looks as follows:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276412" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-userviewmodel_renamed-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="UserViewModel_renamed.cs content, created by dsibinski on 03:12PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="UserViewModel_renamed.cs">
        <tr>
          <td id="file-userviewmodel_renamed-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-userviewmodel_renamed-cs-LC1" class="blob-code blob-code-inner js-file-line">public record UserViewModel(Guid Id, string Name, string LastName, </td>
        </tr>
        <tr>
          <td id="file-userviewmodel_renamed-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-userviewmodel_renamed-cs-LC2" class="blob-code blob-code-inner js-file-line">    string Login, bool IsActive, int FidelityPoints, AddressViewModel? Address = null);</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7e0f39f3c7ffb2010000bb0ea1629701/raw/f40ac01938a57e487280fe35c4f07400d63b7cd9/UserViewModel_renamed.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/7e0f39f3c7ffb2010000bb0ea1629701#file-userviewmodel_renamed-cs" class="Link--inTextBlock">
          UserViewModel_renamed.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Nice! The backend dev is a very good programmer, so (s)he even launches the React web application to make sure that everything still works correctly and there are no errors in the dev console:</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" decoding="async" width="972" height="405" data-attachment-id="4111" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/3_userddatawithoutloyaltypointsdisplayed/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?fit=972%2C405&amp;ssl=1" data-orig-size="972,405" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="3_UserdDataWithoutLoyaltyPointsDisplayed" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?fit=972%2C405&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?resize=972%2C405&#038;ssl=1" alt="Table of users rendered on the web page with empty &quot;Loyalty points&quot; column and no errors on Chrome DevTools console" class="wp-image-4111" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?w=972&amp;ssl=1 972w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?resize=300%2C125&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?resize=768%2C320&amp;ssl=1 768w" sizes="(max-width: 972px) 100vw, 972px" /></figure>



<p>After a quick look, everything looks awesome. The users list is displayed, there are no errors in the console. Apparently, these test users don&#8217;t have any loyalty points assigned &#8211; that&#8217;s why the empty values in &#8220;Loyalty points&#8221; column. What&#8217;s more, translators will update the column&#8217;s translation later. We are good! Let&#8217;s go on prod! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60e.png" alt="😎" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>I guess you already know what went wrong here. <strong>API definition changed, but TypeScript didn&#8217;t inform us about that</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f614.png" alt="😔" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Our <code>UserViewModel</code> still uses the old property name:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="508" height="290" data-attachment-id="4115" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/4_tsoutdateduserviewmodel/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/4_TSOutdatedUserViewModel.png?fit=508%2C290&amp;ssl=1" data-orig-size="508,290" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="4_TSOutdatedUserViewModel" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/4_TSOutdatedUserViewModel.png?fit=508%2C290&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/4_TSOutdatedUserViewModel.png?resize=508%2C290&#038;ssl=1" alt="UserViewModel typescript type definition" class="wp-image-4115" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/4_TSOutdatedUserViewModel.png?w=508&amp;ssl=1 508w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/4_TSOutdatedUserViewModel.png?resize=300%2C171&amp;ssl=1 300w" sizes="auto, (max-width: 508px) 100vw, 508px" /></figure>
</div>


<p>However, it still works. When rendering the <code>UsersList</code>, we simply get <code>undefined</code> in place of <code>loyaltyPoints</code>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="661" height="313" data-attachment-id="4116" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/5_tsoldpropertyundefined/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/5_TSOldPropertyUndefined.png?fit=661%2C313&amp;ssl=1" data-orig-size="661,313" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="5_TSOldPropertyUndefined" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/5_TSOldPropertyUndefined.png?fit=661%2C313&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/5_TSOldPropertyUndefined.png?resize=661%2C313&#038;ssl=1" alt="UsersList rendering at runtime. user.loyaltyPoints property is always undefined" class="wp-image-4116" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/5_TSOldPropertyUndefined.png?w=661&amp;ssl=1 661w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/5_TSOldPropertyUndefined.png?resize=300%2C142&amp;ssl=1 300w" sizes="auto, (max-width: 661px) 100vw, 661px" /></figure>
</div>


<p>In the end, <em>this is <a href="https://www.codejourney.net/2018/11/10-most-shocking-javascript-features-for-csharp-developers/">all JavaScript there</a></em>. What&#8217;s interesting, the renamed <code>fidelityPoints</code> property is already there at runtime:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="441" height="239" data-attachment-id="4117" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/6_newpropertypresentatjsruntime/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?fit=441%2C239&amp;ssl=1" data-orig-size="441,239" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="6_NewPropertyPresentAtJsRuntime" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?fit=441%2C239&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?resize=441%2C239&#038;ssl=1" alt="At runtime we can see the new fidelityPoints property already present" class="wp-image-4117" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?w=441&amp;ssl=1 441w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?resize=300%2C163&amp;ssl=1 300w" sizes="auto, (max-width: 441px) 100vw, 441px" /></figure>
</div>


<p>but no one cared about it <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f614.png" alt="😔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong>With the current solution, we will never be informed soon enough about API models changes in our React application</strong>. In the best case, we&#8217;ll get an <code>undefiend</code> or <code>null</code> error when clicking through the app. However, it&#8217;s usually an end user who finds such problems on production. This is definitely not what we want <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f636.png" alt="😶" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>We can solve this problem by typing API responses with <a href="https://github.com/colinhacks/zod">zod</a>. Let&#8217;s now see how to do that.</p>



<h2 class="wp-block-heading">The Solution &#8211; zod</h2>



<p>Our remedy &#8211; <a href="https://github.com/colinhacks/zod"><code>zod</code></a> &#8211; is quite a <a href="https://www.npmjs.com/package/zod">decent npm package</a> with with ~600k weekly downloads. Its GitHub page advertises the library as <em>TypeScript-first schema validation with static type inference</em>.</p>



<p>You can definitely do many things with <code>zod</code>. It can be used together with libraries like <a href="https://react-hook-form.com/">react-hook-form</a> to perform complex forms validation. However, in our case, <strong>we&#8217;ll treat <code>zod</code> as a solution for better typings in TypeScript</strong>.</p>



<h3 class="wp-block-heading">Adding zod to React app</h3>



<p>First, let&#8217;s install <code>zod</code> into our React application:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
npm i zod
</pre></div>


<h3 class="wp-block-heading">First schema definition with zod</h3>



<p>With <code>zod</code>, we define our types in a slightly different way. Instead of creating a <code>type</code> or <code>interface</code> directly, we first create a <em>schema</em>. In our case, we can define a <code>UserViewModelSchema</code> using <code>z.object</code> creator function:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276653" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-userviewmodel_zodschema-ts" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-typescript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="UserViewModel_ZodSchema.ts content, created by dsibinski on 03:39PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="UserViewModel_ZodSchema.ts">
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-userviewmodel_zodschema-ts-LC1" class="blob-code blob-code-inner js-file-line">export const UserViewModelSchema = z.object({</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-userviewmodel_zodschema-ts-LC2" class="blob-code blob-code-inner js-file-line">  id: z.string().uuid(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-userviewmodel_zodschema-ts-LC3" class="blob-code blob-code-inner js-file-line">  name: z.string(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-userviewmodel_zodschema-ts-LC4" class="blob-code blob-code-inner js-file-line">  lastName: z.string(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-userviewmodel_zodschema-ts-LC5" class="blob-code blob-code-inner js-file-line">  login: z.string(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-userviewmodel_zodschema-ts-LC6" class="blob-code blob-code-inner js-file-line">  isActive: z.boolean(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-userviewmodel_zodschema-ts-LC7" class="blob-code blob-code-inner js-file-line">  loyaltyPoints: z.number(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-userviewmodel_zodschema-ts-LC8" class="blob-code blob-code-inner js-file-line">  address: AddressViewModelSchema.nullable(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-userviewmodel_zodschema-ts-LC9" class="blob-code blob-code-inner js-file-line">});</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/9c7759dff996babccf1b14da276d76c8/raw/959d8bf640a1f20dc10b7975c7a8fa40e62392d5/UserViewModel_ZodSchema.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/9c7759dff996babccf1b14da276d76c8#file-userviewmodel_zodschema-ts" class="Link--inTextBlock">
          UserViewModel_ZodSchema.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Few interesting parts here:</p>



<ul class="wp-block-list"><li><em>Line 2</em>: notice how <code>zod</code> helps us to define types like <code>Guid</code> with built-in schemas like <code>uuid()</code></li><li><em>Line 8</em>: first, I used <code>AddressViewModelSchema</code> here. This is a custom schema of an <code>AddressViewModel</code> object, which is another type used internally in <code>UserViewModel</code>. You can use such custom schemas in other schemas. Also notice the <code>nullable()</code> call here, which makes the <code>address</code> property nullable</li></ul>



<p>First step done &#8211; we have our <code>UserViewModelSchema</code>. But can we use it instead of <code>UserViewModel</code> type? Not really. Schema is used for validation purposes only. We still need the <code>UserViewModel</code> TypeScript&#8217;s type. </p>



<h3 class="wp-block-heading">Inferring type from zod&#8217;s schema</h3>



<p>Fortunately, <code>zod</code> comes with a handy <code>z.infer</code> function that allows us to <em>infer</em> the type from the schema.</p>



<p>Finally, the <code>userViewModel.ts</code> file looks as follows:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276693" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-userviewmodel_zod-ts" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-typescript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="userViewModel_zod.ts content, created by dsibinski on 03:43PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="userViewModel_zod.ts">
        <tr>
          <td id="file-userviewmodel_zod-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-userviewmodel_zod-ts-LC1" class="blob-code blob-code-inner js-file-line">import { z } from &quot;zod&quot;;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-userviewmodel_zod-ts-LC2" class="blob-code blob-code-inner js-file-line">import { AddressViewModelSchema } from &quot;./addressViewModel&quot;;</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-userviewmodel_zod-ts-LC3" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-userviewmodel_zod-ts-LC4" class="blob-code blob-code-inner js-file-line">export const UserViewModelSchema = z.object({</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-userviewmodel_zod-ts-LC5" class="blob-code blob-code-inner js-file-line">  id: z.string().uuid(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-userviewmodel_zod-ts-LC6" class="blob-code blob-code-inner js-file-line">  name: z.string(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-userviewmodel_zod-ts-LC7" class="blob-code blob-code-inner js-file-line">  lastName: z.string(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-userviewmodel_zod-ts-LC8" class="blob-code blob-code-inner js-file-line">  login: z.string(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-userviewmodel_zod-ts-LC9" class="blob-code blob-code-inner js-file-line">  isActive: z.boolean(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-userviewmodel_zod-ts-LC10" class="blob-code blob-code-inner js-file-line">  loyaltyPoints: z.number(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-userviewmodel_zod-ts-LC11" class="blob-code blob-code-inner js-file-line">  address: AddressViewModelSchema.nullable(),</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-userviewmodel_zod-ts-LC12" class="blob-code blob-code-inner js-file-line">});</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-userviewmodel_zod-ts-LC13" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zod-ts-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-userviewmodel_zod-ts-LC14" class="blob-code blob-code-inner js-file-line">export type UserViewModel = z.infer&lt;typeof UserViewModelSchema&gt;;</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/64cb91fade703c4bbf6ade4c6ad84d19/raw/d45af9863a80557b643b3b04c3440287c20a923b/userViewModel_zod.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/64cb91fade703c4bbf6ade4c6ad84d19#file-userviewmodel_zod-ts" class="Link--inTextBlock">
          userViewModel_zod.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>We can use the exported <code>UserViewModel</code> type as previously used type. It&#8217;s an equivalent, inferred from <code>UserViewModelSchema</code>.</p>



<h3 class="wp-block-heading">Validating API responses with zod schema</h3>



<p>One last step is to make use of <code>UserViewModelSchema</code>. Let&#8217;s modify the <code>getAllUsers</code> function from <code>usersService</code> to validate the data received from the API against our schema:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist117276973" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-getallusers_with_zod-ts" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-typescript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="getAllUsers_with_zod.ts content, created by dsibinski on 04:13PM on July 09, 2022."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="getAllUsers_with_zod.ts">
        <tr>
          <td id="file-getallusers_with_zod-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-getallusers_with_zod-ts-LC1" class="blob-code blob-code-inner js-file-line">getAllUsers = async (): Promise&lt;UserViewModel[]&gt; =&gt; {</td>
        </tr>
        <tr>
          <td id="file-getallusers_with_zod-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-getallusers_with_zod-ts-LC2" class="blob-code blob-code-inner js-file-line">  const url = `${this.apiEndpoint}/AllUsers`;</td>
        </tr>
        <tr>
          <td id="file-getallusers_with_zod-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-getallusers_with_zod-ts-LC3" class="blob-code blob-code-inner js-file-line">  const response = await fetch(url);</td>
        </tr>
        <tr>
          <td id="file-getallusers_with_zod-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-getallusers_with_zod-ts-LC4" class="blob-code blob-code-inner js-file-line">  const usersJson = await response.json();</td>
        </tr>
        <tr>
          <td id="file-getallusers_with_zod-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-getallusers_with_zod-ts-LC5" class="blob-code blob-code-inner js-file-line">  const users = z.array(UserViewModelSchema).parse(usersJson);</td>
        </tr>
        <tr>
          <td id="file-getallusers_with_zod-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-getallusers_with_zod-ts-LC6" class="blob-code blob-code-inner js-file-line">  return users;</td>
        </tr>
        <tr>
          <td id="file-getallusers_with_zod-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-getallusers_with_zod-ts-LC7" class="blob-code blob-code-inner js-file-line">};</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/ac10bdf2e256f549939d6eeed68067aa/raw/d996f3ee73f81ada41ee15ac3fadf14064992acc/getAllUsers_with_zod.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/ac10bdf2e256f549939d6eeed68067aa#file-getallusers_with_zod-ts" class="Link--inTextBlock">
          getAllUsers_with_zod.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Notice the usage of <code>z.array</code>. This function call tells <code>zod</code> to validate an array of objects meeting the rules defined by <code>UserViewModelSchema</code>, not a single object.</p>



<p>Now, let&#8217;s run our React app and see what happens when we click the &#8220;Fetch users&#8221; button:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="651" height="592" data-attachment-id="4121" data-permalink="https://www.codejourney.net/typing-api-responses-with-zod/7_zodschemavalidationerror/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/7_ZodSchemaValidationError.png?fit=651%2C592&amp;ssl=1" data-orig-size="651,592" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="7_ZodSchemaValidationError" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/7_ZodSchemaValidationError.png?fit=651%2C592&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/7_ZodSchemaValidationError.png?resize=651%2C592&#038;ssl=1" alt="zod throws schema validation error on Chrome dev tools console" class="wp-image-4121" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/7_ZodSchemaValidationError.png?w=651&amp;ssl=1 651w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/7_ZodSchemaValidationError.png?resize=300%2C273&amp;ssl=1 300w" sizes="auto, (max-width: 651px) 100vw, 651px" /></figure>
</div>


<p>This is awesome! Exactly what we wanted &#8211; a <strong>schema validation error for API response</strong>. Notice how the <strong>error message precisely points to the missing (or wrong, in other cases) property.</strong> It tells us we expected a <code>number</code> called <code>loyaltyPoints</code>, but instead we received <code>undefined</code>. The reason for this error message is that the <code>loyaltyPoints</code> field is <code>Required</code> in our schema.</p>



<p>After renaming <code>loyaltyPoints</code> to <code>fidelityPoints</code> in <code>UserViewModelSchema</code> and updating the <code>UsersList</code> component accordingly, everything works fine again. </p>



<p>We are now fully typed and prepared for the future, in case an issue with desynchronization of frontend and backend typings happens again <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Summary</h2>



<p>Today, we&#8217;ve seen how typing API responses with <code>zod</code> can help us detect frontend and backend models desynchronization. Schema validation throws errors when the data doesn&#8217;t match its expected shape. </p>



<p>Remember that <code>zod</code> is an extended library with many options. I recommend <a href="https://github.com/colinhacks/zod">exploring them</a> on your own. An interesting feature we didn&#8217;t cover in this article is <a href="https://github.com/colinhacks/zod#strict">strict mode</a>, which doesn&#8217;t allow additional fields not present in the schema definition when validating the data object. </p>



<p>The open question remains whether to use schema validation on production. One could think that it&#8217;s better to not throw any validation errors, because <em>JavaScript may just work</em>. However, I think that throwing an error is always better than <em>silently</em> letting things through. An error lets programmers, automated tests or manual testers to detect the issue before the end user does <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>You can explore the complete code presented in this article <a href="https://github.com/dsibinski/DotNetReactZodApp">here</a>.</p>
<p>The post <a href="https://www.codejourney.net/typing-api-responses-with-zod/">Typing API Responses With Zod</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/typing-api-responses-with-zod/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4093</post-id>	</item>
		<item>
		<title>How To Fix SqlException Database Is Not Currently Available On Azure (0x80131904)</title>
		<link>https://www.codejourney.net/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/</link>
					<comments>https://www.codejourney.net/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 17 May 2022 05:32:15 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[microsoft azure]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4036</guid>

					<description><![CDATA[<p>I recently deployed my .NET 6 application to Microsoft Azure. The app uses NHibernate for working with SQL Server database. After some time, I started getting an unhandled exception when opening the application: The database is not currently available was very interesting to me. I struggled a bit with solving that, so if you want&#8230;</p>
<p>The post <a href="https://www.codejourney.net/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/">How To Fix SqlException Database Is Not Currently Available On Azure (0x80131904)</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I recently deployed my .NET 6 application to Microsoft Azure. The app uses <a href="https://nhibernate.info/">NHibernate</a> for working with SQL Server database. After some time, I started getting an unhandled exception when opening the application:</p>



<pre class="wp-block-code"><code>NHibernate.Exceptions.GenericADOException: could not load an entity: 
...
 ---&gt; Microsoft.Data.SqlClient.SqlException (0x80131904): <strong>Database 'myappdb' on server 'myapp.database.windows.net' is not currently available</strong>.  Please retry the connection later.  If the problem persists, contact customer support, and provide them the session tracing ID of '{EB501CF2-2F21-4E28-9042-2B83EEE57B91}'.</code></pre>



<p>The <em>database is</em> <em>not currently available </em>was very interesting to me. I struggled a bit with solving that, so if you want to know how I did it &#8211; continue reading <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<span id="more-4036"></span>



<h2 class="wp-block-heading">The problem</h2>



<p>My .NET 6 app is an <a href="https://azure.microsoft.com/en-us/services/app-service/">Azure App Service</a>, and it uses SQL Server database. Quite standard Azure stuff.</p>



<p>The issue was that when opening the ASP.NET web app after some time of inactivity, there was an HTTP 500 error. When I checked the logs, the full error looked as follows:</p>



<pre class="wp-block-code"><code><strong>NHibernate.Exceptions.GenericADOException: could not load an entity</strong>: &#91;MyApp.Infrastructure.DomainObjects.ApplicationUser#37931c5a376748d7a49f215ca30283a2]&#91;SQL: SELECT applicatio0_.applicationuser_key as id1_3_0_, applicatio0_1_.UserName as username2_3_0_, applicatio0_1_.NormalizedUserName as normalizedusername3_3_0_, applicatio0_1_.Email as email4_3_0_, applicatio0_1_.NormalizedEmail as normalizedemail5_3_0_, applicatio0_1_.EmailConfirmed as emailconfirmed6_3_0_, applicatio0_1_.PhoneNumber as phonenumber7_3_0_, applicatio0_1_.PhoneNumberConfirmed as phonenumberconfirmed8_3_0_, applicatio0_1_.LockoutEnabled as lockoutenabled9_3_0_, applicatio0_1_.LockoutEnd as lockoutend10_3_0_, applicatio0_1_.AccessFailedCount as accessfailedcount11_3_0_, applicatio0_1_.ConcurrencyStamp as concurrencystamp12_3_0_, applicatio0_1_.PasswordHash as passwordhash13_3_0_, applicatio0_1_.TwoFactorEnabled as twofactorenabled14_3_0_, applicatio0_1_.SecurityStamp as securitystamp15_3_0_ FROM ApplicationUsers applicatio0_ inner join dbo.AspNetUsers applicatio0_1_ on applicatio0_.applicationuser_key=applicatio0_1_.Id WHERE applicatio0_.applicationuser_key=?]
 ---&gt; Microsoft.Data.SqlClient.SqlException (0x80131904): <strong>Database 'myappdb' on server 'myapp.database.windows.net' is not currently available</strong>.  Please retry the connection later.  If the problem persists, contact customer support, and provide them the session tracing ID of '{EB501CF2-2F21-4E28-2342-2B836E35E891}'.
   at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)</code></pre>



<p>There were two characteristics of this error:</p>



<ul class="wp-block-list"><li>it always appeared after some time of not using the web app</li><li>I never reproduced it locally</li></ul>



<p>So it must have been something wrong with Azure.</p>



<h2 class="wp-block-heading">Transient issues in Azure databases</h2>



<p>First thing I did, obviously, was checking Azure App Service logs. This is what I found:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="288" data-attachment-id="4053" data-permalink="https://www.codejourney.net/azure_database_transient_problems/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?fit=1482%2C417&amp;ssl=1" data-orig-size="1482,417" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Azure_database_transient_problems" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?fit=1024%2C288&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?resize=1024%2C288&#038;ssl=1" alt="Error log when database is not currently available error occured in Azure" class="wp-image-4053" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?resize=1024%2C288&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?resize=300%2C84&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?resize=768%2C216&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?w=1482&amp;ssl=1 1482w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>The first recommended step got me curious. <em>To reduce the impact of connection issues caused by future reconfiguration, <strong>please implement retry logic in your code</strong></em>.</p>



<p>So I started reading. There&#8217;s even <a href="https://docs.microsoft.com/en-us/aspnet/aspnet/overview/developing-apps-with-windows-azure/building-real-world-cloud-apps-with-windows-azure/transient-fault-handling">official Microsoft documentation for that</a>. It basically says that <em>in the cloud environment you&#8217;ll find that failed and dropped database connections happen periodically.</em></p>



<p>I must admit it seemed quite new to me. However, I started digging into that. I used <a href="https://github.com/App-vNext/Polly">Polly</a> to implement the retry logic in my app. I found few places where there was an NHibernate query for fetching users executed and wrapped it into the retry policy.</p>



<p>Nothing worked. I was still getting the error. Then, after some talks with my coworkers, we found the real reason behind that&#8230;</p>



<h2 class="wp-block-heading">Solution: Azure database tier</h2>



<p>When talking about the issue with my teammates, someone mentioned that the databases in Azure are <em>serverless</em> by default.</p>



<p>I logged into the <a href="https://portal.azure.com/">Azure Portal</a> and checked the &#8220;Compute + storage&#8221; settings my SQL database my app used:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="382" data-attachment-id="4055" data-permalink="https://www.codejourney.net/azure_tier_settings_serverless/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?fit=1193%2C445&amp;ssl=1" data-orig-size="1193,445" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Azure_tier_settings_serverless" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?fit=1024%2C382&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?resize=1024%2C382&#038;ssl=1" alt="Azure Portal and Service and compute tier settings of SQL Database set to General Purpose. Reason for database is not currently available error" class="wp-image-4055" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?resize=1024%2C382&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?resize=300%2C112&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?resize=768%2C286&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?w=1193&amp;ssl=1 1193w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>Indeed, the tier selected was &#8220;General purpose (Scalable compute and storage options)&#8221; with &#8220;Serverless&#8221; compute tier selected.</p>



<p>I changed it to &#8220;Basic (For less demanding workloads)&#8221;:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="507" data-attachment-id="4056" data-permalink="https://www.codejourney.net/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/azure_tier_settings_basic/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?fit=1188%2C588&amp;ssl=1" data-orig-size="1188,588" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Azure_tier_settings_basic" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?fit=1024%2C507&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?resize=1024%2C507&#038;ssl=1" alt="Azure Portal and tier of the SQL database changed to Basic. It made database is not currently available error disappear" class="wp-image-4056" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?resize=1024%2C507&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?resize=300%2C148&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?resize=768%2C380&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?w=1188&amp;ssl=1 1188w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>and&#8230; it worked <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92f.png" alt="🤯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> All errors saying that the database is not currently available disappeared. I also removed all Polly-related code for retry policies.</p>



<h2 class="wp-block-heading">A little explanation</h2>



<p>Why do serverless databases in Azure behave like that?</p>



<p>I finally found this explanation in the <a href="https://docs.microsoft.com/en-us/azure/azure-sql/database/serverless-tier-overview?view=azuresql">Microsoft documentation</a>:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>If a serverless database is paused, then <strong>the first login will resume the database and return an error stating that the database is unavailable with error code 40613</strong>. Once the database is resumed, the login must be retried to establish connectivity</p></blockquote>



<p>That blew my mind! It means that the <em>database is not currently available</em> exception is expected. There&#8217;s also another part there:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Database clients with connection retry logic should not need to be modified. For connection retry logic options that are built-in to the SqlClient driver, see&nbsp;<a href="https://docs.microsoft.com/en-us/sql/connect/ado-net/configurable-retry-logic">configurable retry logic in SqlClient</a>.</p></blockquote>



<p>Apparently, users of ORMs like Entity Framework <a href="https://docs.microsoft.com/en-us/ef/ef6/fundamentals/connection-resiliency/retry-logic">should not have to worry about those issues</a>. Unfortunately, NHibernate doesn&#8217;t have such built-in transient errors retry logic. That&#8217;s why I experienced this particular issue and couldn&#8217;t find any straightforward solution online. Simply not many people (if anyone at all? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f601.png" alt="😁" class="wp-smiley" style="height: 1em; max-height: 1em;" />) experienced this before.</p>



<p>If you want even more details and context, check out this article: <a href="https://kohera.be/azure-cloud/should-i-use-serverless-for-all-my-azure-sql-databases/">SHOULD I USE SERVERLESS FOR ALL MY AZURE SQL DATABASES?</a></p>



<h2 class="wp-block-heading">What if I want to use serverless Azure database?</h2>



<p>Well&#8230; if you really want to use the serverless features of Azure, you might be struggling with NHibernate. As I mentioned, apparently there&#8217;s no built-in transient failures retry mechanism in the ORM. There&#8217;s one promising solution <a href="https://github.com/MRCollective/NHibernate.SqlAzure">here</a>. However, currently it&#8217;s build for NHibernate 3.3.1.4000, so it doesn&#8217;t work with the current version. There&#8217;s a <a href="https://github.com/MRCollective/NHibernate.SqlAzure/pull/37">Pull Request</a> and an <a href="https://github.com/MRCollective/NHibernate.SqlAzure/issues/32">issue</a> opened for upgrading it to the newest version and .NET 6/7. Let&#8217;s hope it is done soon.</p>



<p>Otherwise, you can try using <a href="https://www.codejourney.net/2022/05/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/">Polly</a> as I did initially. However, I didn&#8217;t manage to make fully working.</p>



<p>If you have any other idea or solution &#8211; let us know in the comments below.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>I hope this article saves you some hours of debugging, so you can quickly solve this <em>database is not currently available</em> error in Azure. I wish I found this article on another website few weeks ago <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/">How To Fix SqlException Database Is Not Currently Available On Azure (0x80131904)</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/how-to-fix-sqlexception-database-is-not-currently-available-on-azure-0x80131904/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4036</post-id>	</item>
		<item>
		<title>C# 8: Default Interface Methods Implementation</title>
		<link>https://www.codejourney.net/csharp-8-default-interface-methods/</link>
					<comments>https://www.codejourney.net/csharp-8-default-interface-methods/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 20 Feb 2019 14:00:25 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#8.0]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3495</guid>

					<description><![CDATA[<p>Continuing to examine new C# 8 features, today we are taking a look at a bit controversial one. It&#8217;s a possibility to provide default interface methods implementation. How will this possibility change the way we write C#? Why is it being introduced? I&#8217;ll try to address these questions today 🙂 Interfaces today As we all&#8230;</p>
<p>The post <a href="https://www.codejourney.net/csharp-8-default-interface-methods/">C# 8: Default Interface Methods Implementation</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Continuing to examine <a rel="noreferrer noopener" aria-label="new C# 8 features (opens in a new tab)" href="https://www.codejourney.net/tag/c8-0/" target="_blank">new C# 8 features</a>, today we are taking a look at a bit controversial one. It&#8217;s a possibility to provide <strong>default interface methods</strong> <strong>implementation</strong>. </p>



<p>How will this possibility change the way we write C#? Why is it being introduced? I&#8217;ll try to address these questions today <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<span id="more-3495"></span>



<h2 class="wp-block-heading">Interfaces today</h2>



<p>As we all know from the current version of C#, interfaces allow to define a kind of contract, which must be respected by a class implementing it. Today interfaces can only contain definitions of methods (with no body). These methods are then actually implemented by concrete classes. If a class doesn&#8217;t implement all of its interface&#8217;s methods, compiler produces an error.</p>



<p>What&#8217;s problematic in this approach? Assuming that you have the following interface and class(es) implementing it:</p>



<figure class="wp-block-embed aligncenter"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94701778" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-interfaceandclass-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="InterfaceAndClass.cs content, created by dsibinski on 05:42PM on February 17, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="InterfaceAndClass.cs">
        <tr>
          <td id="file-interfaceandclass-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-interfaceandclass-cs-LC1" class="blob-code blob-code-inner js-file-line">  interface IDeveloper</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-interfaceandclass-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-interfaceandclass-cs-LC3" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language, DateTime dueDate);</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-interfaceandclass-cs-LC4" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-interfaceandclass-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-interfaceandclass-cs-LC6" class="blob-code blob-code-inner js-file-line">  class BackendDev : IDeveloper</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-interfaceandclass-cs-LC7" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-interfaceandclass-cs-LC8" class="blob-code blob-code-inner js-file-line">      public void LearnNewLanguage(string language, DateTime dueDate)</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-interfaceandclass-cs-LC9" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-interfaceandclass-cs-LC10" class="blob-code blob-code-inner js-file-line">          // Learning new language&#8230;</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-interfaceandclass-cs-LC11" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-interfaceandclass-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-interfaceandclass-cs-LC12" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7b5c3454e4976c1b96ac97500be949fc/raw/cb6412facda3f0b612bc289084dcb211536a6e2c/InterfaceAndClass.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/7b5c3454e4976c1b96ac97500be949fc#file-interfaceandclass-cs" class="Link--inTextBlock">
          InterfaceAndClass.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>


<p>With time, you may want to extend <span style="color: #ff6600;">IDeveloper</span> interface by adding a new method, for instance:</p>


<figure class="wp-block-embed aligncenter"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94701794" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-interfacemodified-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="InterfaceModified.cs content, created by dsibinski on 05:44PM on February 17, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="InterfaceModified.cs">
        <tr>
          <td id="file-interfacemodified-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-interfacemodified-cs-LC1" class="blob-code blob-code-inner js-file-line">  interface IDeveloper</td>
        </tr>
        <tr>
          <td id="file-interfacemodified-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-interfacemodified-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-interfacemodified-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-interfacemodified-cs-LC3" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language, DateTime dueDate);  </td>
        </tr>
        <tr>
          <td id="file-interfacemodified-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-interfacemodified-cs-LC4" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language); // new method added</td>
        </tr>
        <tr>
          <td id="file-interfacemodified-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-interfacemodified-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/509cee33619a492fe29555d0039230f9/raw/557c447d23512860c9af5b2563b3d17d7256d598/InterfaceModified.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/509cee33619a492fe29555d0039230f9#file-interfacemodified-cs" class="Link--inTextBlock">
          InterfaceModified.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Now you have a problem, because the <strong>new method must be implemented in all places where the interface was used</strong>. Compiler gives you an error as long as it&#8217;s not done: </p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="900" height="400" data-attachment-id="3508" data-permalink="https://www.codejourney.net/csharp-8-default-interface-methods/interfacemembernotimplemented-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?fit=900%2C400&amp;ssl=1" data-orig-size="900,400" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="InterfaceMemberNotImplemented" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?fit=900%2C400&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?resize=900%2C400&#038;ssl=1" alt="C# 8: Default Interface Methods Implementation: C# compilation error - interface member not implemented" class="wp-image-3508" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?w=900&amp;ssl=1 900w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?resize=300%2C133&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?resize=768%2C341&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?resize=676%2C300&amp;ssl=1 676w" sizes="auto, (max-width: 900px) 100vw, 900px" /><figcaption>C# compilation error &#8211; interface member not implemented</figcaption></figure>


<p>If your interface is used in many places, also by another teams or developers (which is often the case in reality), <strong>this is a breaking change <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></strong></p>
<p>It may be really painful, depending on how extensively your interface is used. In any case, all classes based on the <span style="color: #ff6600;">IDeveloper</span> interface must implement the new <span style="color: #ff6600;">LearnNewLanguage(string language)</span> method. Only then the code compiles.</p>
<p>One of the reasons for&nbsp;<a href="https://github.com/dotnet/csharplang/issues/52" target="_blank" rel="noopener">introducing into C# default interface methods</a> is to avoid such breaking changes scenarios <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<h2 class="wp-block-heading">Default Interface Methods</h2>



<p>As we can read in the <a rel="noreferrer noopener" aria-label="feature's design notes (opens in a new tab)" href="https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md" target="_blank">feature&#8217;s design notes</a>, an inspiration for it is a similar concept already alive in Java &#8211; <em><a rel="noreferrer noopener" aria-label="Default Methods (opens in a new tab)" href="https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html" target="_blank">Default Methods</a></em>.</p>



<p>The main idea of this new C# feature is a possibility to <strong>provide a default implementation of an interface&#8217;s method</strong>.</p>



<h3 class="wp-block-heading">Realization in C# 8.0</h3>



<p>In our example using C# 8.0 we&#8217;ll be able to implement it as follows:</p>



<figure class="wp-block-embed aligncenter"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94702032" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-defaultinterfacemethod-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="DefaultInterfaceMethod.cs content, created by dsibinski on 06:08PM on February 17, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="DefaultInterfaceMethod.cs">
        <tr>
          <td id="file-defaultinterfacemethod-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-defaultinterfacemethod-cs-LC1" class="blob-code blob-code-inner js-file-line">  interface IDeveloper</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-defaultinterfacemethod-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-defaultinterfacemethod-cs-LC3" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language, DateTime dueDate);</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-defaultinterfacemethod-cs-LC4" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-defaultinterfacemethod-cs-LC5" class="blob-code blob-code-inner js-file-line">      {   </td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-defaultinterfacemethod-cs-LC6" class="blob-code blob-code-inner js-file-line">          // default implementation</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-defaultinterfacemethod-cs-LC7" class="blob-code blob-code-inner js-file-line">          LearnNewLanguage(language, DateTime.Now.AddMonths(6));</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-defaultinterfacemethod-cs-LC8" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-defaultinterfacemethod-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/1c6e54a566eb9854cd18f7a535fb116b/raw/8285fe2333fd7ba4a713d9953dc19e9c50fc1c71/DefaultInterfaceMethod.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/1c6e54a566eb9854cd18f7a535fb116b#file-defaultinterfacemethod-cs" class="Link--inTextBlock">
          DefaultInterfaceMethod.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>


<p>In that case, our class implementing the <span style="color: #ff6600;">IDeveloper</span> interface can legally not implement this new method and there will be no compilation error:</p>


<figure class="wp-block-embed aligncenter"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94702168" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-defaultinterfacemethod_usage-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="DefaultInterfaceMethod_usage.cs content, created by dsibinski on 06:22PM on February 17, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="DefaultInterfaceMethod_usage.cs">
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC1" class="blob-code blob-code-inner js-file-line">  interface IDeveloper</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC3" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language, DateTime dueDate);</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC4" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC5" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC6" class="blob-code blob-code-inner js-file-line">          // default implementation</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC7" class="blob-code blob-code-inner js-file-line">          LearnNewLanguage(language, DateTime.Now.AddMonths(6));</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC8" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC11" class="blob-code blob-code-inner js-file-line">  class BackendDev : IDeveloper // compiles OK</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC12" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC13" class="blob-code blob-code-inner js-file-line">      public void LearnNewLanguage(string language, DateTime dueDate)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC14" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC15" class="blob-code blob-code-inner js-file-line">          // Learning new language&#8230;</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC16" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC17" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC18" class="blob-code blob-code-inner js-file-line">  </td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC19" class="blob-code blob-code-inner js-file-line">  class Program</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC20" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC21" class="blob-code blob-code-inner js-file-line">      static void Main(string[] args)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC22" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC23" class="blob-code blob-code-inner js-file-line">          IDeveloper dev = new BackendDev();</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC24" class="blob-code blob-code-inner js-file-line">          dev.LearnNewLanguage(&quot;Rust&quot;); // OK &#8211; default implementation of</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC25" class="blob-code blob-code-inner js-file-line">                                        // IDeveloper.LearnNewLanguage(string language) is called</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC26" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
          <td id="file-defaultinterfacemethod_usage-cs-LC27" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/1a1af2c889fe5f101c59e65cf1107b3b/raw/aa6a0e5f0be3e2696d0b978410bf44d1fece564d/DefaultInterfaceMethod_usage.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/1a1af2c889fe5f101c59e65cf1107b3b#file-defaultinterfacemethod_usage-cs" class="Link--inTextBlock">
          DefaultInterfaceMethod_usage.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>


<p>Notice that it only works when&nbsp;<span style="color: #ff6600;">BackendDev</span> is contextually treated as <span style="color: #ff6600;">IDeveloper</span>. It means that a class doesn&#8217;t inherit members from the interfaces it implements:</p>


<figure class="wp-block-embed aligncenter"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94704015" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-defaultinterfacemethod_usage_nok-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="DefaultInterfaceMethod_usage_NOK.cs content, created by dsibinski on 09:19PM on February 17, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="DefaultInterfaceMethod_usage_NOK.cs">
        <tr>
          <td id="file-defaultinterfacemethod_usage_nok-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-defaultinterfacemethod_usage_nok-cs-LC1" class="blob-code blob-code-inner js-file-line">  BackendDev dev = new BackendDev();	          </td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage_nok-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-defaultinterfacemethod_usage_nok-cs-LC2" class="blob-code blob-code-inner js-file-line">  dev.LearnNewLanguage(&quot;Rust&quot;); // compilation error: class &#39;BackendDev&#39; </td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_usage_nok-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-defaultinterfacemethod_usage_nok-cs-LC3" class="blob-code blob-code-inner js-file-line">                                // does not contain a member &#39;LearnNewLanguage&#39;</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/4a9a2ccf9163390d9c52b86e7491a055/raw/0572886c2ec17de6a38719a3e96c1d2a373964b4/DefaultInterfaceMethod_usage_NOK.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/4a9a2ccf9163390d9c52b86e7491a055#file-defaultinterfacemethod_usage_nok-cs" class="Link--inTextBlock">
          DefaultInterfaceMethod_usage_NOK.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<h3 class="wp-block-heading">What about multiple inheritance?</h3>



<p>As some of you probably realized, this new feature exposes C# to a <a rel="noreferrer noopener" aria-label="multiple inheritance problem (opens in a new tab)" href="https://en.wikipedia.org/wiki/Multiple_inheritance" target="_blank">multiple inheritance problem</a> (also known as <em>Diamond of Death</em>). So far C# didn&#8217;t have this issue, because we can only inherit from a single class. We can implement multiple interfaces, but so far the interfaces couldn&#8217;t provide methods&#8217; implementation. Because of that, there was no <em>Diamond of Death</em> possible. Soon it&#8217;s gonna change <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h4 class="wp-block-heading"><strong>Diamond of Death in C# 8</strong></h4>



<p>In case of C# default interface methods we may illustrate this issue with the following code:</p>



<figure class="wp-block-embed aligncenter"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94702504" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-defaultinterfacemethod_diamondofdeath-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="DefaultInterfaceMethod_DiamondOfDeath.cs content, created by dsibinski on 06:53PM on February 17, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="DefaultInterfaceMethod_DiamondOfDeath.cs">
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC1" class="blob-code blob-code-inner js-file-line">  interface IDeveloper</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC3" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC4" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC5" class="blob-code blob-code-inner js-file-line">          Console.Write($&quot;Learning {language} in a default way.&quot;);</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC6" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC7" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC9" class="blob-code blob-code-inner js-file-line">  interface IBackendDev : IDeveloper</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC10" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC11" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC12" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC13" class="blob-code blob-code-inner js-file-line">          Console.Write($&quot;Learning {language} in a backend way.&quot;);</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC14" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC15" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC17" class="blob-code blob-code-inner js-file-line">  interface IFrontendDev : IDeveloper</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC18" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC19" class="blob-code blob-code-inner js-file-line">      void LearnNewLanguage(string language)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC20" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC21" class="blob-code blob-code-inner js-file-line">          Console.Write($&quot;Learning {language} in a frontend way.&quot;);</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC22" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC23" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC24" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC25" class="blob-code blob-code-inner js-file-line">  interface IFullStackDev : IBackendDev, IFrontendDev { } // uses default implementation, </td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC26" class="blob-code blob-code-inner js-file-line">                                                          // of LearnNewLanguage, but which one?</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC27" class="blob-code blob-code-inner js-file-line">  class Dev : IFullStackDev { }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC28" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC29" class="blob-code blob-code-inner js-file-line">  class Program</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC30" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC31" class="blob-code blob-code-inner js-file-line">      static void Main(string[] args)</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC32" class="blob-code blob-code-inner js-file-line">      {</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC33" class="blob-code blob-code-inner js-file-line">          IFullStackDev dev = new Dev();</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC34" class="blob-code blob-code-inner js-file-line">          dev.LearnNewLanguage(&quot;TypeScript&quot;); // which method is called? The one</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC35" class="blob-code blob-code-inner js-file-line">                                              // from IBackendDev or IFrontendDev?</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC36" class="blob-code blob-code-inner js-file-line">      }</td>
        </tr>
        <tr>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
          <td id="file-defaultinterfacemethod_diamondofdeath-cs-LC37" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/883f8f3b867572d9108ebe2048d62ee2/raw/39ad6f21746130f40cf0a48c17111032e0885335/DefaultInterfaceMethod_DiamondOfDeath.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/883f8f3b867572d9108ebe2048d62ee2#file-defaultinterfacemethod_diamondofdeath-cs" class="Link--inTextBlock">
          DefaultInterfaceMethod_DiamondOfDeath.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p><em>Please note that the syntax or places in which compiler generates errors may still change in the final feature&#8217;s version.</em></p>



<p>To better illustrate this Diamond of Death example, take a look at the following diagram:</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="801" height="332" data-attachment-id="3526" data-permalink="https://www.codejourney.net/csharp-8-default-interface-methods/diamondofdeath-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?fit=801%2C332&amp;ssl=1" data-orig-size="801,332" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="DiamondOfDeath" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?fit=801%2C332&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?resize=801%2C332&#038;ssl=1" alt="C# 8: Default Interface Methods Implementation: Diamond of Death example illustration" class="wp-image-3526" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?w=801&amp;ssl=1 801w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?resize=300%2C124&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?resize=768%2C318&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?resize=676%2C280&amp;ssl=1 676w" sizes="auto, (max-width: 801px) 100vw, 801px" /><figcaption>Diamond of Death example illustration</figcaption></figure>



<p>The question is: <strong>which method should be called in such case?</strong></p>



<h4 class="wp-block-heading"><strong>Solution: most specific override rule</strong></h4>



<p>C# 8.0 will solve this issue by introducing <a rel="noreferrer noopener" aria-label="the most specific override rule (opens in a new tab)" href="https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md#the-most-specific-override-rule" target="_blank">the most specific override rule</a>. It means that in our case illustrated above, the <strong>compiler will issue an error and won&#8217;t let us do this</strong>.</p>


<p>To avoid this ambiguity, we&#8217;ll be forced to implement or override <span style="color: #ff6600;">LearnNewLanguage(string language)</span> in <span style="color: #ff6600;">IFullStackDev</span> interface. Only then it will be considered the most specific version of the method in the interfaces hierarchy we have. It will then be used when calling the method on objects contextually treated as instances of <span style="color: #ff6600;">IFullStackDev</span>. We could also implement it directly in the <span style="color: #ff6600;">Dev</span> class and use the class (not interface) type. It would then call the most specific method from the class. This way multiple inheritance issue will be eliminated.</p>


<h2 class="wp-block-heading">Compiler for the rescue</h2>



<p>There are a lot of other potential ambiguity scenarios that may take place after introducing into C# default interface methods. You can check all of them with potential solutions <a rel="noreferrer noopener" aria-label="are well-discussed on GitHub (opens in a new tab)" href="https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md" target="_blank">well-discussed on GitHub</a>.</p>



<p>The general assumption is that <strong>all code which may lead to issues related to default interface methods implementations is detected by the compiler</strong>. In effect, we should get appropriate errors when compiling the source code. That way, programmer can fix all potential conflicts directly when these arise.</p>



<h2 class="wp-block-heading">What about .NET Framework?</h2>



<p>What&#8217;s interesting with default interface methods is that <strong>it requres changes in the runtime</strong>. According to <a rel="noreferrer noopener" aria-label="current assumptions (opens in a new tab)" href="https://www.youtube.com/watch?v=HW_FnmnDlGQ&amp;feature=youtu.be&amp;t=3279" target="_blank">current assumptions</a>, it means that <strong>this feature will not work with .NET Framework</strong>! Only CoreCLR and Mono stack runtimes are going to receive these new updates.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>As the motivation for introducing into C# default interface methods the language team members mention possibility to interact with some Android and iOS APIs, which already support such feature. They also claim that C# will get the <em><a rel="noreferrer noopener" aria-label="traits programming language feature (opens in a new tab)" href="https://en.wikipedia.org/wiki/Trait_(computer_programming)" target="_blank">traits</a></em><a rel="noreferrer noopener" aria-label="traits programming language feature (opens in a new tab)" href="https://en.wikipedia.org/wiki/Trait_(computer_programming)" target="_blank"> programming language feature</a> with default interface methods.</p>



<p>In my opinion this is the most controversial from all <a rel="noreferrer noopener" aria-label="C# 8.0 new features (opens in a new tab)" href="https://www.codejourney.net/tag/c8-0/" target="_blank">C# 8.0 new features</a>. It completely changes something which was obviousness for the developers for years. Probably we&#8217;ll see less breaking changes issues when the interfaces are extended, but <a rel="noreferrer noopener" aria-label="looking on the list of issues and edge cases it produces (opens in a new tab)" href="https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md" target="_blank">looking on the list of issues and edge cases it produces</a>&#8230; Maybe assuming it already works in a similar way in Java we should just accept it? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Another interesting, .NET-specific aspect is that this feature will not work with .NET Framework. It&#8217;s probably the very first moment when the difference in pace between .NET Core and Framework is so explicit.</p>



<p>I&#8217;m also very curious about the performance implications of default interface methods. I&#8217;ll for sure be following this issue on GitHub to see how it evolves <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong><u class="remove-format">What do you think? Is it a good idea to introduce default interface methods into C#?</u></strong></p>
<p>The post <a href="https://www.codejourney.net/csharp-8-default-interface-methods/">C# 8: Default Interface Methods Implementation</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/csharp-8-default-interface-methods/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3495</post-id>	</item>
		<item>
		<title>C# 8: Slicing with Indexes and Ranges</title>
		<link>https://www.codejourney.net/csharp-8-slicing-indexes-ranges/</link>
					<comments>https://www.codejourney.net/csharp-8-slicing-indexes-ranges/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 13 Feb 2019 14:00:02 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#8.0]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3454</guid>

					<description><![CDATA[<p>C# 8.0 brings us another nice feature called slicing. In order to make it possible, two new concepts are introduced: Indexes and Ranges. Let&#8217;s see how this tiny feature is supposed to make our life easier 🙂 Goal of slicing The main purpose of introducing slicing into the language is to make working with arrays&#8230;</p>
<p>The post <a href="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/">C# 8: Slicing with Indexes and Ranges</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>C# 8.0 brings us another nice feature called <strong>slicing</strong>. In order to make it possible, two new concepts are introduced: Indexes and Ranges.</p>



<p>Let&#8217;s see how this tiny feature is supposed to make our life easier <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<span id="more-3454"></span>



<h2 class="wp-block-heading">Goal of slicing</h2>



<p>The main purpose of introducing slicing into the language is to make  working with arrays and strings easier.</p>



<p>Currently, when you want to retrieve a fragment of an array (X elements from the array, located for instance in its middle), you can use LINQ, i.e. combination of <a rel="noreferrer noopener" aria-label="Take (opens in a new tab)" href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take?view=netframework-4.7.2" target="_blank">Take</a> and <a rel="noreferrer noopener" aria-label="Skip (opens in a new tab)" href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skip?view=netframework-4.7.2" target="_blank">Skip</a> methods. You can also <a rel="noreferrer noopener" aria-label="create some extension method (opens in a new tab)" href="https://www.dotnetperls.com/array-slice" target="_blank">create some extension method</a> to provide kind of slicing.</p>



<p>To illustrate the current way, using LINQ to retrieve only 2nd, 3rd and 4th elements of an array looks as follows:</p>



<figure class="wp-block-embed"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94580774" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-arrayslicewithlinq-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="ArraySliceWithLinq.cs content, created by dsibinski on 01:22PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="ArraySliceWithLinq.cs">
        <tr>
          <td id="file-arrayslicewithlinq-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-arrayslicewithlinq-cs-LC1" class="blob-code blob-code-inner js-file-line">  var array = new[] { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39; , &#39;H&#39;};</td>
        </tr>
        <tr>
          <td id="file-arrayslicewithlinq-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-arrayslicewithlinq-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-arrayslicewithlinq-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-arrayslicewithlinq-cs-LC3" class="blob-code blob-code-inner js-file-line">  var arraySlice = array.Skip(1).Take(3).ToArray(); // contains &#39;B&#39;, &#39;C&#39; and &#39;D&#39;</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c13e6535c6601b033c5d6285a4908305/raw/916b574f79a9b821194d00f0c2fb999ca81ac3fa/ArraySliceWithLinq.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/c13e6535c6601b033c5d6285a4908305#file-arrayslicewithlinq-cs" class="Link--inTextBlock">
          ArraySliceWithLinq.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>C# community and designers decided it&#8217;s not convenient enough, so are <a rel="noreferrer noopener" aria-label="now adding&nbsp;to&nbsp;C#&nbsp;indexes&nbsp;and&nbsp;ranges&nbsp;(in&nbsp;order to provide slicing) (opens in a new tab)" href="https://github.com/dotnet/csharplang/issues/185" target="_blank">now adding&nbsp;to&nbsp;C#&nbsp;8 indexes&nbsp;and&nbsp;ranges&nbsp;(in&nbsp;order to provide slicing)</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Index</h2>


<p>C# 8.0 comes along with a new object &#8211; <span style="color: #ff6600;">System.Index</span>. It&#8217;s a structure internally and looks as follows:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1016" height="486" data-attachment-id="3460" data-permalink="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/indexstruct/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?fit=1016%2C486&amp;ssl=1" data-orig-size="1016,486" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="IndexStruct" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?fit=1016%2C486&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?resize=1016%2C486&#038;ssl=1" alt="C# 8 indexes and ranges: System.Index structure - .NET Core 3.0.0-preview-27324-5" class="wp-image-3460" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?w=1016&amp;ssl=1 1016w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?resize=300%2C144&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?resize=768%2C367&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?resize=676%2C323&amp;ssl=1 676w" sizes="auto, (max-width: 1016px) 100vw, 1016px" /><figcaption>System.Index <em>s</em>tructure &#8211; .NET Core 3.0.0-preview-27324-5</figcaption></figure>


<p>What&#8217;s interesting here, is that the constructor takes the <span style="color: #ff6600;">value</span> of the <span style="color: #000000;">index </span>and boolean flag <span style="color: #ff6600;">fromEnd</span>. Let&#8217;s see how we can use it in practice:</p>


<figure class="wp-block-embed"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94584228" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-indexescsharp8-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="IndexesCsharp8.cs content, created by dsibinski on 04:11PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="IndexesCsharp8.cs">
        <tr>
          <td id="file-indexescsharp8-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-indexescsharp8-cs-LC1" class="blob-code blob-code-inner js-file-line">  var array = new[] { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39; };</td>
        </tr>
        <tr>
          <td id="file-indexescsharp8-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-indexescsharp8-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-indexescsharp8-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-indexescsharp8-cs-LC3" class="blob-code blob-code-inner js-file-line">  Index idx1 = 2;  // 2nd element from the beginning</td>
        </tr>
        <tr>
          <td id="file-indexescsharp8-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-indexescsharp8-cs-LC4" class="blob-code blob-code-inner js-file-line">  Index idx2 = ^3; // 3rd element from the end (^)</td>
        </tr>
        <tr>
          <td id="file-indexescsharp8-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-indexescsharp8-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-indexescsharp8-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-indexescsharp8-cs-LC6" class="blob-code blob-code-inner js-file-line">  Console.WriteLine($&quot;{array[idx1]}, {array[idx2]}&quot;); // prints &quot;C, F&quot;</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/798ba2d501ecdbca5c4fe29e5c4ff5a3/raw/32ecae5f14941b2f4ee01ad5d47cf76a05d06739/IndexesCsharp8.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/798ba2d501ecdbca5c4fe29e5c4ff5a3#file-indexescsharp8-cs" class="Link--inTextBlock">
          IndexesCsharp8.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>While the first printed value is nothing special, as you can see we can now use the <strong>hat operator</strong> (^) in order to <strong>index from the end</strong>. The following also works:</p>



<figure class="wp-block-embed"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94584292" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-indexes_ccharp8_2-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Indexes_CCharp8_2.cs content, created by dsibinski on 04:14PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Indexes_CCharp8_2.cs">
        <tr>
          <td id="file-indexes_ccharp8_2-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-indexes_ccharp8_2-cs-LC1" class="blob-code blob-code-inner js-file-line">  var array = new[] { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39; };</td>
        </tr>
        <tr>
          <td id="file-indexes_ccharp8_2-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-indexes_ccharp8_2-cs-LC2" class="blob-code blob-code-inner js-file-line">  Console.WriteLine($&quot;{array[^3]}&quot;); // prints &quot;F&quot; (3rd element from the end)</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/1065a08b53aa7b0e5eb9ca19a3285f19/raw/3af3373353f98f3e0e9ae9d47db0168af5251dcf/Indexes_CCharp8_2.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/1065a08b53aa7b0e5eb9ca19a3285f19#file-indexes_ccharp8_2-cs" class="Link--inTextBlock">
          Indexes_CCharp8_2.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>


<p>It means that the ^ operator is a syntactic sugar for<span style="color: #ff6600;"> Index</span>. I allowed myself to check the IL produced:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="824" height="376" data-attachment-id="3461" data-permalink="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/indexctorsyntacticsugerhat/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?fit=824%2C376&amp;ssl=1" data-orig-size="824,376" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="IndexCtorSyntacticSugerHat" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?fit=824%2C376&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?resize=824%2C376&#038;ssl=1" alt="C# 8 indexes and ranges: IL Code behind ^ (hat operator)" class="wp-image-3461" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?w=824&amp;ssl=1 824w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?resize=300%2C137&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?resize=768%2C350&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?resize=676%2C308&amp;ssl=1 676w" sizes="auto, (max-width: 824px) 100vw, 824px" /><figcaption>IL Code behind ^ (hat operator)</figcaption></figure>


<p>As we suspected &#8211; an instance of <span style="color: #ff6600;">Index</span> is created, passing <strong>3</strong> as <span style="color: #ff6600;">value</span> and <strong>true</strong> as <span style="color: #ff6600;">fromEnd</span>&nbsp;(see the constructor parameters above).</p>


<h2 class="wp-block-heading">Range</h2>


<p>Another concept which uses Indexes is a new structural data type &#8211; <span style="color: #ff6600;">System.Range</span>:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1012" height="478" data-attachment-id="3463" data-permalink="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/rangeusingindexes/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?fit=1012%2C478&amp;ssl=1" data-orig-size="1012,478" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="RangeUsingIndexes" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?fit=1012%2C478&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?resize=1012%2C478&#038;ssl=1" alt="C# 8 indexes and ranges: System.Range structure - .NET Core 3.0.0-preview-27324-5" class="wp-image-3463" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?w=1012&amp;ssl=1 1012w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?resize=768%2C363&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?resize=676%2C319&amp;ssl=1 676w" sizes="auto, (max-width: 1012px) 100vw, 1012px" /><figcaption> <em>System.Range structure &#8211; .NET Core 3.0.0-preview-27324-5</em> </figcaption></figure>



<p>As you can see, it <strong>really uses Indexes</strong>. We can even try creating it on our own:</p>



<figure class="wp-block-embed"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94584738" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-rangecsharp8-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="RangeCSharp8.cs content, created by dsibinski on 04:35PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="RangeCSharp8.cs">
        <tr>
          <td id="file-rangecsharp8-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-rangecsharp8-cs-LC1" class="blob-code blob-code-inner js-file-line">  var array = new[] { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39; };</td>
        </tr>
        <tr>
          <td id="file-rangecsharp8-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-rangecsharp8-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-rangecsharp8-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-rangecsharp8-cs-LC3" class="blob-code blob-code-inner js-file-line">  Range r = Range.Create(2, ^1); // range from 2nd to </td>
        </tr>
        <tr>
          <td id="file-rangecsharp8-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-rangecsharp8-cs-LC4" class="blob-code blob-code-inner js-file-line">                                 // 1st element from the end</td>
        </tr>
        <tr>
          <td id="file-rangecsharp8-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-rangecsharp8-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-rangecsharp8-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-rangecsharp8-cs-LC6" class="blob-code blob-code-inner js-file-line">  Console.WriteLine(array[r]); // prints &quot;CDEFG&quot;</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/6621a3ca282c539274851b4bba11c8cf/raw/57acffc675f86be754fef1a451198fa2480ab2a4/RangeCSharp8.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/6621a3ca282c539274851b4bba11c8cf#file-rangecsharp8-cs" class="Link--inTextBlock">
          RangeCSharp8.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>


<p>This doesn&#8217;t really make extracting data from the arrays better than <em>Skip-Take</em> LINQ, does it?</p>
<p>Fortunately, there&#8217;s another friendly C# language element introduced called <em>range expression</em>. It can be written as <span style="color: #ff6600;">x..y</span> and used directly for indexing:</p>
<p><style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94584820" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-rangeexpression-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="RangeExpression.cs content, created by dsibinski on 04:39PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="RangeExpression.cs">
        <tr>
          <td id="file-rangeexpression-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-rangeexpression-cs-LC1" class="blob-code blob-code-inner js-file-line">  var array = new[] { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39; };</td>
        </tr>
        <tr>
          <td id="file-rangeexpression-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-rangeexpression-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-rangeexpression-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-rangeexpression-cs-LC3" class="blob-code blob-code-inner js-file-line">  Console.WriteLine(array[2..^1]); // prints &quot;CDEFG&quot;</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/28e64583ab06c323d1154548b48a271e/raw/fb2cd5b0d63f54247e3bc0d8322c7aa88d81eb21/RangeExpression.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/28e64583ab06c323d1154548b48a271e#file-rangeexpression-cs" class="Link--inTextBlock">
          RangeExpression.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>
</p>
<p>This looks much better! Let&#8217;s see how C# compiler translated our 2 lines of code by looking at the pseudo-C# IL produced:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="504" height="640" data-attachment-id="3464" data-permalink="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/rangearrayilcsharp/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeArrayILCSharp.png?fit=504%2C640&amp;ssl=1" data-orig-size="504,640" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="RangeArrayILCSharp" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeArrayILCSharp.png?fit=504%2C640&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeArrayILCSharp.png?resize=504%2C640&#038;ssl=1" alt="C# 8 indexes and ranges: IL (C# pseudo-code) produced when using range expression" class="wp-image-3464" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeArrayILCSharp.png?w=504&amp;ssl=1 504w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeArrayILCSharp.png?resize=236%2C300&amp;ssl=1 236w" sizes="auto, (max-width: 504px) 100vw, 504px" /><figcaption>IL (C# pseudo-code) produced when using range expression</figcaption></figure>



<p>Even though we could achieve the same with much less LINQ, C# compiler does a lot of stuff for us, keeping our code simpler to grasp.</p>



<h4 class="wp-block-heading"><strong>Ranges in strings</strong></h4>


<p>All these operations apply also to <span style="color: #ff6600;">strings</span>:</p>
<p><style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94585049" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-csharp8_rangestring-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="CSharp8_RangeString.cs content, created by dsibinski on 04:49PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="CSharp8_RangeString.cs">
        <tr>
          <td id="file-csharp8_rangestring-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-csharp8_rangestring-cs-LC1" class="blob-code blob-code-inner js-file-line">  var story = &quot;C# 8 is going to be great!&quot;;</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangestring-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-csharp8_rangestring-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangestring-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-csharp8_rangestring-cs-LC3" class="blob-code blob-code-inner js-file-line">  Console.WriteLine(story[^6..^0]); // prints &quot;great!&quot; (last 6 chars)</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/6f011df284ea03178178cceed6f902b4/raw/1c33e97219a57324005049b9f182916934932784/CSharp8_RangeString.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/6f011df284ea03178178cceed6f902b4#file-csharp8_rangestring-cs" class="Link--inTextBlock">
          CSharp8_RangeString.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>
</p>
<p></p>


<h4 class="wp-block-heading"><strong>Ranges in foreach loop</strong></h4>


<p>Next interesting usage is in the <span style="color: #ff6600;">foreach</span> loop:</p>
<p><style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist94585228" class="gist">
    <div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
      <div class="gist-data">
        
<div class="js-gist-file-update-container js-task-list-container">
      <div id="file-csharp8_rangeforeach-cs" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="CSharp8_RangeForeach.cs content, created by dsibinski on 05:00PM on February 11, 2019."
    >

        
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
    <span>
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a>
    </span>


  <div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters
</a>
</div>
</div></template>
<template class="js-line-alert-template">
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e">
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="CSharp8_RangeForeach.cs">
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-csharp8_rangeforeach-cs-LC1" class="blob-code blob-code-inner js-file-line">  var devs = new Developer[]</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-csharp8_rangeforeach-cs-LC2" class="blob-code blob-code-inner js-file-line">        {</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-csharp8_rangeforeach-cs-LC3" class="blob-code blob-code-inner js-file-line">            new Developer(&quot;Dawid&quot;),</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-csharp8_rangeforeach-cs-LC4" class="blob-code blob-code-inner js-file-line">            new Developer(&quot;Mark&quot;),</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-csharp8_rangeforeach-cs-LC5" class="blob-code blob-code-inner js-file-line">            new Developer(&quot;John&quot;),</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-csharp8_rangeforeach-cs-LC6" class="blob-code blob-code-inner js-file-line">            new Developer(&quot;Alice&quot;),</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-csharp8_rangeforeach-cs-LC7" class="blob-code blob-code-inner js-file-line">            new Developer(&quot;Kate&quot;)</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-csharp8_rangeforeach-cs-LC8" class="blob-code blob-code-inner js-file-line">        };</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-csharp8_rangeforeach-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-csharp8_rangeforeach-cs-LC10" class="blob-code blob-code-inner js-file-line">  foreach (var dev in devs[1..^2]) // prints &quot;MarkJohn&quot;</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-csharp8_rangeforeach-cs-LC11" class="blob-code blob-code-inner js-file-line">  {</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-csharp8_rangeforeach-cs-LC12" class="blob-code blob-code-inner js-file-line">      Console.Write(dev.FirstName);</td>
        </tr>
        <tr>
          <td id="file-csharp8_rangeforeach-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-csharp8_rangeforeach-cs-LC13" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/92b499a8c0567c88001f7338d149c519/raw/529e6f6428932ace2f5a2932beca25f33947f88b/CSharp8_RangeForeach.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/92b499a8c0567c88001f7338d149c519#file-csharp8_rangeforeach-cs" class="Link--inTextBlock">
          CSharp8_RangeForeach.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>
</p>


<h2 class="wp-block-heading">Summary</h2>



<p>I see these &#8220;little&#8221; C# 8 indexes and ranges as another helpful feature. It&#8217;s less breaking and controversial than <a rel="noreferrer noopener" aria-label="nullable reference types (opens in a new tab)" href="https://www.codejourney.net/2019/02/csharp-8-nullable-reference-types/" target="_blank">nullable reference types</a>, still making us write less C# code in the future.</p>



<p>If you&#8217;d like to dig the feature even more, I encourage you to read the <a rel="noreferrer noopener" aria-label="discussions about it on GItHub, (opens in a new tab)" href="https://github.com/dotnet/csharplang/issues/198" target="_blank">discussions about it on GitHub,</a> which I always find very interesting <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Developers, what do you think about C# 8 indexes and ranges? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/">C# 8: Slicing with Indexes and Ranges</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/csharp-8-slicing-indexes-ranges/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3454</post-id>	</item>
		<item>
		<title>C# 8: Nullable Reference Types</title>
		<link>https://www.codejourney.net/csharp-8-nullable-reference-types/</link>
					<comments>https://www.codejourney.net/csharp-8-nullable-reference-types/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 05 Feb 2019 14:00:14 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#8.0]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3406</guid>

					<description><![CDATA[<p>In the few next posts I&#8217;d like to share with you some of the most interesting C# 8.0 features. Today we&#8217;re going to start with examining nullable reference types. Let&#8217;s see then 🙂 Learn about building C# 8.0 C# 8.0 is going to be the next major release of C# language. It should be released&#8230;</p>
<p>The post <a href="https://www.codejourney.net/csharp-8-nullable-reference-types/">C# 8: Nullable Reference Types</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the few next posts I&#8217;d like to share with you some of the most interesting C# 8.0 features. Today we&#8217;re going to start with examining nullable reference types. Let&#8217;s see then <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<span id="more-3406"></span>



<h2 class="wp-block-heading">Learn about building C# 8.0</h2>


<p>C# 8.0 is going to be the next major release of C# language. It should be released by the same time as .NET Core 3.0.</p>
<p>What I find very interesting is <a href="https://github.com/dotnet/csharplang" target="_blank" rel="noopener">C# language GitHub repository</a>. Among others, you can find there very interesting <a href="https://github.com/dotnet/csharplang/tree/master/meetings" target="_blank" rel="noopener">notes from C# language design meetings</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If you filter well, you can also list so called &#8220;proposals&#8221;, which are current candidates for new C#&#8217;s version (or sub-versions) features. By clicking <a href="https://github.com/dotnet/csharplang/issues?q=is%3Aissue+milestone%3A%228.0+candidate%22+is%3Aopen" target="_blank" rel="noopener">here</a> you can list C# 8.0 candidates.</p>
<p>I will publish a separate post regarding each feature which I find particularly interesting <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<h2 class="wp-block-heading">Nullable reference types</h2>



<p>First of the C# 8.0 features I&#8217;d like to discuss are <a rel="noreferrer noopener" aria-label="nullable reference types (opens in a new tab)" href="https://github.com/dotnet/csharplang/issues/36" target="_blank">nullable reference types</a>. It seems it&#8217;s going to change the way we write our code, so it&#8217;s worth knowing this feature.</p>



<h3 class="wp-block-heading">A bit of history &#8211; NullReferenceException</h3>


<p>Consider the following code:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="586" height="679" data-attachment-id="3422" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/nullrefcode/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullRefCode.png?fit=586%2C679&amp;ssl=1" data-orig-size="586,679" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NullRefCode" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullRefCode.png?fit=586%2C679&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullRefCode.png?resize=586%2C679&#038;ssl=1" alt="" class="wp-image-3422" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullRefCode.png?w=586&amp;ssl=1 586w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullRefCode.png?resize=259%2C300&amp;ssl=1 259w" sizes="auto, (max-width: 586px) 100vw, 586px" /><figcaption>Gist: <a href="https://gist.github.com/dsibinski/c1c9fabb9f05c1e1fed6a58278dce7e5" target="_blank" rel="noreferrer noopener" aria-label="NullCode.cs (opens in a new tab)">NullCode.cs</a></figcaption></figure>


<p>Guess what happens after executing this as a console app? Of course, our favorite <span style="color: #ff6600;">NullReferenceException</span> is thrown:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="199" data-attachment-id="3423" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/nullreferenceexception-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?fit=1109%2C216&amp;ssl=1" data-orig-size="1109,216" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NullReferenceException" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?fit=1024%2C199&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?resize=1024%2C199&#038;ssl=1" alt="" class="wp-image-3423" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?resize=1024%2C199&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?resize=300%2C58&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?resize=768%2C150&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?resize=676%2C132&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?w=1109&amp;ssl=1 1109w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>


<p>In this case, <span style="color: #ff6600;">jsDev.LastName</span> is of course set to <span style="color: #ff6600;">null</span>.</p>
<p><span style="color: #ff6600;">NullReferenceException</span> has been a nightmare for thousands of developers (and users) for many years. What if, in the cases like our example, we knew before that in this place our object might be <span style="color: #ff6600;">null</span>?</p>


<h3 class="wp-block-heading">New world &#8211; #nullable enable</h3>


<p>For that purpose, C# development team is introducing <strong>nullable reference types</strong>. In essence, it<strong> makes reference types (like <span style="color: #ff6600;">string</span>) non-nullable</strong>! However to not be a tough nut to crack, all issues related to assigning <span style="color: #ff6600;">null</span> value to non-nullable reference types are presented as warnings, not errors.</p>


<p>In order to use this feature, you need to enable it.  You can do it with a preprocessor directive <em>#nullable enabled.</em> We can do it directly in the source code file. In the future, it <a rel="noreferrer noopener" aria-label="should also be possible (opens in a new tab)" href="https://github.com/dotnet/project-system/issues/4058" target="_blank">should also be possible</a> to enable it on project level.</p>



<p>Notice what happens when we enable it in our example:</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="616" height="405" data-attachment-id="3425" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/propertynotinitializedwarning/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarning.png?fit=616%2C405&amp;ssl=1" data-orig-size="616,405" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="PropertyNotInitializedWarning" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarning.png?fit=616%2C405&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarning.png?resize=616%2C405&#038;ssl=1" alt="" class="wp-image-3425" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarning.png?w=616&amp;ssl=1 616w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarning.png?resize=300%2C197&amp;ssl=1 300w" sizes="auto, (max-width: 616px) 100vw, 616px" /></figure>


<p>We&#8217;re still able to compile, but this nice warning is displayed <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> As soon as we initialize <span style="color: #ff6600;">LastName</span> property in the constructor, the warning disappears:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="656" height="405" data-attachment-id="3426" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/propertynotinitializedwarningdisappeared/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarningDisappeared.png?fit=656%2C405&amp;ssl=1" data-orig-size="656,405" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="PropertyNotInitializedWarningDisappeared" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarningDisappeared.png?fit=656%2C405&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarningDisappeared.png?resize=656%2C405&#038;ssl=1" alt="" class="wp-image-3426" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarningDisappeared.png?w=656&amp;ssl=1 656w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarningDisappeared.png?resize=300%2C185&amp;ssl=1 300w" sizes="auto, (max-width: 656px) 100vw, 656px" /></figure>



<p>If you try to cheat, it still works like a charm <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> :</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="870" height="418" data-attachment-id="3427" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/nullassignationnonnullablestring/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?fit=870%2C418&amp;ssl=1" data-orig-size="870,418" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NullAssignationNonnullableString" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?fit=870%2C418&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?resize=870%2C418&#038;ssl=1" alt="" class="wp-image-3427" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?w=870&amp;ssl=1 870w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?resize=300%2C144&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?resize=768%2C369&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?resize=676%2C325&amp;ssl=1 676w" sizes="auto, (max-width: 870px) 100vw, 870px" /></figure>


<p>But hey&#8230; what if you actually want <span style="color: #ff6600;">null</span> in this particular <span style="color: #ff6600;">string</span>? <strong>You need to explicitly mark your reference type variable as nullable</strong>. You probably recall nullable value types like <span style="color: #ff6600;">int?</span>, don&#8217;t you (read <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">this post</a> if you don&#8217;t remember the difference between value and reference types)? Now you can do the same with non-nullable reference types:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="491" height="342" data-attachment-id="3428" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/nullablereferencestring/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableReferenceString.png?fit=491%2C342&amp;ssl=1" data-orig-size="491,342" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NullableReferenceString" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableReferenceString.png?fit=491%2C342&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableReferenceString.png?resize=491%2C342&#038;ssl=1" alt="" class="wp-image-3428" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableReferenceString.png?w=491&amp;ssl=1 491w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableReferenceString.png?resize=300%2C209&amp;ssl=1 300w" sizes="auto, (max-width: 491px) 100vw, 491px" /></figure>



<p>Nonetheless, in such case, the compiler still takes care of us:</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="774" height="210" data-attachment-id="3429" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/possiblenullwarning/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?fit=774%2C210&amp;ssl=1" data-orig-size="774,210" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="PossibleNullWarning" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?fit=774%2C210&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?resize=774%2C210&#038;ssl=1" alt="" class="wp-image-3429" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?w=774&amp;ssl=1 774w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?resize=300%2C81&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?resize=768%2C208&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?resize=676%2C183&amp;ssl=1 676w" sizes="auto, (max-width: 774px) 100vw, 774px" /></figure>


<p>The final fix is quite obvious &#8211; we need to check for <span style="color: #ff6600;">null</span> first:</p>


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="691" height="195" data-attachment-id="3430" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/checkingfornull/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?fit=691%2C195&amp;ssl=1" data-orig-size="691,195" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="CheckingForNull" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?fit=691%2C195&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?resize=691%2C195&#038;ssl=1" alt="" class="wp-image-3430" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?w=691&amp;ssl=1 691w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?resize=300%2C85&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?resize=676%2C191&amp;ssl=1 676w" sizes="auto, (max-width: 691px) 100vw, 691px" /></figure>



<p>At this stage all warnings finally disappear. You can find the finished source code <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="https://gist.github.com/dsibinski/67c6d315463186bbfa4281dbb6611a25" target="_blank">here</a>.</p>



<h3 class="wp-block-heading">Nullable reference types in IL</h3>



<p>The only thing I found in the IL code compiled from source code with <em>#nullable enabled</em> directive was NullableAttribute applied to properties:</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="878" height="328" data-attachment-id="3440" data-permalink="https://www.codejourney.net/csharp-8-nullable-reference-types/nullablereftypesil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?fit=878%2C328&amp;ssl=1" data-orig-size="878,328" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NullableRefTypesIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?fit=878%2C328&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?resize=878%2C328&#038;ssl=1" alt="" class="wp-image-3440" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?w=878&amp;ssl=1 878w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?resize=300%2C112&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?resize=768%2C287&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?resize=676%2C253&amp;ssl=1 676w" sizes="auto, (max-width: 878px) 100vw, 878px" /></figure>



<p>It seems that nullable reference types are implemented by applying this attribute to variables, which is only used by the compiler (runtime is not affected).</p>



<h2 class="wp-block-heading">Summary</h2>



<p>I&#8217;m really excited about nullable reference types in C# 8. I personally feel that it even introduces some clarity in the language &#8211; we&#8217;ll have explicit declarations for nullable value and reference types. However, in more complex scenarios it may bring some confusion in regards to reference types and using &#8220;?&#8221; character (like generics or collections &#8211; see <a href="https://codeblog.jonskeet.uk/2018/04/21/first-steps-with-nullable-reference-types/" target="_blank" rel="noreferrer noopener" aria-label="Jon Skeet's post (opens in a new tab)">Jon Skeet&#8217;s post</a> for more details). For sure it&#8217;s a significant step towards eliminating issues with exceptions caused by null references.</p>



<p>What do you think about nullable reference types? Is it a good direction in which C# language is going? Share your thoughts in the comments! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/csharp-8-nullable-reference-types/">C# 8: Nullable Reference Types</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/csharp-8-nullable-reference-types/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3406</post-id>	</item>
		<item>
		<title>[.NET Internals 10] Application execution model</title>
		<link>https://www.codejourney.net/net-internals-10-application-execution-model/</link>
					<comments>https://www.codejourney.net/net-internals-10-application-execution-model/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 11 Oct 2018 18:46:40 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2907</guid>

					<description><![CDATA[<p>Knowing the idea and main benefits of JIT compilation from the previous post, we&#8217;ll now see how it fits into .NET applications execution model. By execution model I mean a process of having a .NET Framework application actually executed on the machine (CPU), starting from having its source code written. It contains all steps and&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-10-application-execution-model/">[.NET Internals 10] Application execution model</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Knowing the idea and main benefits of JIT compilation <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">from the previous post</a>, we&#8217;ll now see how it fits into .NET applications execution model.</p>
<p>By <em>execution model</em> I mean a process of having a .NET Framework application actually executed on the machine (CPU), starting from having its source code written. It contains all steps and actions necessary to happen in order to transform source code (like C#) into machine (assembly) code and execute it.</p>
<p><span id="more-2907"></span></p>
<h1>.NET languages standardization</h1>
<p>As we all know, .NET is just an execution platform. There are, however, a lot of programming languages which allow us to write code which can then be executed by the platform-specific (not language-specific!) CLR. In order to give programming languages&#8217; creators a set of rules which their language and its compiler must meet to be .NET-compliant, Microsoft defined a <em>Common Language Infrastructure</em> (CLI, also referred to as MSIL in the old days <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ) which is also standardized by ISO and ECMA.</p>
<p>&nbsp;</p>
<p>The main goal of it is to define how the source code should be compiled to the Common Intermediate Language (CIL). As we <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">already know</a>, the CIL should have a standardized format, because it&#8217;s then JIT-compiled to a platform-specific assembly code. Some of the most common implementations of CLI are .NET Framework, .NET Core and Mono. I recommend you to check <a href="http://mattwarren.org/2018/10/02/A-History-of-.NET-Runtimes/" target="_blank" rel="noopener">Matt Warren&#8217;s article on .NET Runtimes history</a> as well <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>&nbsp;</p>
<p>Common Language Infrastructure implies also some other aspects of the programming language and its compiler, including Common Type System, language-agnostic metadata and Common Language Specification. You can read more about it for instance <a href="https://en.wikipedia.org/wiki/Common_Language_Infrastructure" target="_blank" rel="noopener">here</a>.</p>
<p>This all allows us to use various programming languages, like C#, VB.NET, F# or JScript .NET to develop .NET applications. Anyone can still implement their own own .NET language &#8211; it &#8220;just&#8221; needs to conform to the standards.</p>
<p>There&#8217;s also another term <a href="https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/" target="_blank" rel="noopener">introduced somewhat around .NET Core</a> &#8211; <em>.NET Standard</em>. Its purpose is to allow code sharing between various .NET implementations. It actually defines a set of APIs that each .NET platform should implement. More details <a href="https://docs.microsoft.com/en-us/dotnet/standard/net-standard" target="_blank" rel="noopener">here</a>.</p>
<p>This whole <em>standardization</em> makes us arriving to the .NET applications execution model, which is how every standards-compliant CLR application is executed.</p>
<h1>.NET execution model</h1>
<p>Independently of the language of choice, .NET application&#8217;s execution model can be described as the following <strong>4-steps process</strong>:</p>
<ol>
<li>Writing source code in a programming language of choice, including the usage of its compiler</li>
<li>Compiling source code to Common Intermediate Language (CIL)</li>
<li>Compiling CIL into native code &#8211; details of this step <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">in the previous post</a></li>
<li>Execution of the native code.</li>
</ol>
<p>These steps are well-resented on the schema below and then described in details in the next sections.</p>
<p>&nbsp;</p>
<p><figure id="attachment_2917" aria-describedby="caption-attachment-2917" style="width: 639px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2917" data-permalink="https://www.codejourney.net/net-internals-10-application-execution-model/netexecutionmodel/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?fit=639%2C697&amp;ssl=1" data-orig-size="639,697" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NetExecutionModel" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?fit=639%2C697&amp;ssl=1" class="wp-image-2917 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?resize=639%2C697&#038;ssl=1" alt="" width="639" height="697" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?w=639&amp;ssl=1 639w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?resize=275%2C300&amp;ssl=1 275w" sizes="auto, (max-width: 639px) 100vw, 639px" /></a><figcaption id="caption-attachment-2917" class="wp-caption-text"><span style="font-size: 8pt;">.NET application execution model, <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<h2>Writing source code in a programming language of choice</h2>
<p>As mentioned before, .NET applications can be implemented using any language of choice, which is compliant with CLI. Another important part is a <strong>compiler</strong> &#8211; it defines a general syntax of the language, kinds of data types that can be used by a programmer etc. For instance, current open-source compiler for C# and Visual Basic is <a href="https://github.com/dotnet/roslyn" target="_blank" rel="noopener">Roslyn</a>.</p>
<p>In the end, role of the compiler is to <strong>transform the source code to its CIL equivalent</strong>.</p>
<p>The simplest possible complete application written in C# can look as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92409303" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-csharp_code-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="csharp_code.cs content, created by dsibinski on 05:45PM on October 11, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="csharp_code.cs">
<tr>
<td id="file-csharp_code-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-csharp_code-cs-LC1" class="blob-code blob-code-inner js-file-line">  using System;</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-csharp_code-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-csharp_code-cs-LC3" class="blob-code blob-code-inner js-file-line">  public class Program</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-csharp_code-cs-LC4" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-csharp_code-cs-LC5" class="blob-code blob-code-inner js-file-line">      public static void Main()</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-csharp_code-cs-LC6" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-csharp_code-cs-LC7" class="blob-code blob-code-inner js-file-line">          Console.WriteLine(&quot;Hello Readers!&quot;);</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-csharp_code-cs-LC8" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-csharp_code-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7bdc8b50b6d5faefa7f90659e16db696/raw/258d3ec59d80cd06d9ae2cc7b23d9b97dabced47/csharp_code.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7bdc8b50b6d5faefa7f90659e16db696#file-csharp_code-cs" class="Link--inTextBlock"><br />
          csharp_code.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<h2>Compiling source code to CIL</h2>
<p>After the source code is written, it must be compiled to CIL, which is an intermediate language understood by the CLR. On this level, the whole execution process <strong>becomes language-agnostic</strong>, which means that as soon as the code is compiled to CIL it is executed by the CLR and programming language’s features (e.g. its compiler) don&#8217;t play any more role.</p>
<p>CIL code looks more like assembly code, however containing some specific instructions. It&#8217;s still far more readable than native code. Apart from the direct transcript of source code, CIL contains metadata about the DLL/EXE assembly file.</p>
<p>The C# fragment presented in the previous section compiled to CIL by Roslyn looks as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92409385" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-roslyn_msil-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="roslyn_msil.cs content, created by dsibinski on 05:50PM on October 11, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="roslyn_msil.cs">
<tr>
<td id="file-roslyn_msil-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-roslyn_msil-cs-LC1" class="blob-code blob-code-inner js-file-line">  //  Microsoft (R) .NET Framework IL Disassembler.  Version 4.0.30319.33440</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-roslyn_msil-cs-LC2" class="blob-code blob-code-inner js-file-line">  //  Copyright (c) Microsoft Corporation.  All rights reserved.</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-roslyn_msil-cs-LC3" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-roslyn_msil-cs-LC4" class="blob-code blob-code-inner js-file-line">  // Metadata version: v4.0.30319</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-roslyn_msil-cs-LC5" class="blob-code blob-code-inner js-file-line">  .assembly extern mscorlib</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-roslyn_msil-cs-LC6" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-roslyn_msil-cs-LC7" class="blob-code blob-code-inner js-file-line">  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-roslyn_msil-cs-LC8" class="blob-code blob-code-inner js-file-line">  .ver 4:0:0:0</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-roslyn_msil-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-roslyn_msil-cs-LC10" class="blob-code blob-code-inner js-file-line">  .assembly &#39;0bigfb2c&#39;</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-roslyn_msil-cs-LC11" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-roslyn_msil-cs-LC12" class="blob-code blob-code-inner js-file-line">  .hash algorithm 0x00008004</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-roslyn_msil-cs-LC13" class="blob-code blob-code-inner js-file-line">  .ver 0:0:0:0</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-roslyn_msil-cs-LC14" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-roslyn_msil-cs-LC15" class="blob-code blob-code-inner js-file-line">  .module &#39;0bigfb2c.dll&#39;</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-roslyn_msil-cs-LC16" class="blob-code blob-code-inner js-file-line">  // MVID: {3DD8C852-9FE1-4825-8784-3D7200409F2F}</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-roslyn_msil-cs-LC17" class="blob-code blob-code-inner js-file-line">  .imagebase 0x10000000</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-roslyn_msil-cs-LC18" class="blob-code blob-code-inner js-file-line">  .file alignment 0x00000200</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-roslyn_msil-cs-LC19" class="blob-code blob-code-inner js-file-line">  .stackreserve 0x00100000</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-roslyn_msil-cs-LC20" class="blob-code blob-code-inner js-file-line">  .subsystem 0x0003       // WINDOWS_CUI</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-roslyn_msil-cs-LC21" class="blob-code blob-code-inner js-file-line">  .corflags 0x00000001    //  ILONLY</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-roslyn_msil-cs-LC22" class="blob-code blob-code-inner js-file-line">  // Image base: 0x01580000</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-roslyn_msil-cs-LC23" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-roslyn_msil-cs-LC24" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-roslyn_msil-cs-LC25" class="blob-code blob-code-inner js-file-line">  // =============== CLASS MEMBERS DECLARATION ===================</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-roslyn_msil-cs-LC26" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-roslyn_msil-cs-LC27" class="blob-code blob-code-inner js-file-line">  .class public auto ansi beforefieldinit Program</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-roslyn_msil-cs-LC28" class="blob-code blob-code-inner js-file-line">  extends[mscorlib] System.Object</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
<td id="file-roslyn_msil-cs-LC29" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
<td id="file-roslyn_msil-cs-LC30" class="blob-code blob-code-inner js-file-line">  .method public hidebysig static void Main() cil managed</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
<td id="file-roslyn_msil-cs-LC31" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
<td id="file-roslyn_msil-cs-LC32" class="blob-code blob-code-inner js-file-line">  // </td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
<td id="file-roslyn_msil-cs-LC33" class="blob-code blob-code-inner js-file-line">  .maxstack  8</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
<td id="file-roslyn_msil-cs-LC34" class="blob-code blob-code-inner js-file-line">  IL_0000:  nop</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
<td id="file-roslyn_msil-cs-LC35" class="blob-code blob-code-inner js-file-line">  IL_0001:  ldstr      &quot;Hello Readers!&quot;</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
<td id="file-roslyn_msil-cs-LC36" class="blob-code blob-code-inner js-file-line">  IL_0006:  call       void [mscorlib]</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
<td id="file-roslyn_msil-cs-LC37" class="blob-code blob-code-inner js-file-line">  System.Console::WriteLine(string)</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L38" class="blob-num js-line-number js-blob-rnum" data-line-number="38"></td>
<td id="file-roslyn_msil-cs-LC38" class="blob-code blob-code-inner js-file-line">  IL_000b:  nop</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L39" class="blob-num js-line-number js-blob-rnum" data-line-number="39"></td>
<td id="file-roslyn_msil-cs-LC39" class="blob-code blob-code-inner js-file-line">  IL_000c:  ret</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L40" class="blob-num js-line-number js-blob-rnum" data-line-number="40"></td>
<td id="file-roslyn_msil-cs-LC40" class="blob-code blob-code-inner js-file-line">  } // end of method Program::Main</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L41" class="blob-num js-line-number js-blob-rnum" data-line-number="41"></td>
<td id="file-roslyn_msil-cs-LC41" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L42" class="blob-num js-line-number js-blob-rnum" data-line-number="42"></td>
<td id="file-roslyn_msil-cs-LC42" class="blob-code blob-code-inner js-file-line">  .method public hidebysig specialname rtspecialname</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L43" class="blob-num js-line-number js-blob-rnum" data-line-number="43"></td>
<td id="file-roslyn_msil-cs-LC43" class="blob-code blob-code-inner js-file-line">  instance void  .ctor() cil managed</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L44" class="blob-num js-line-number js-blob-rnum" data-line-number="44"></td>
<td id="file-roslyn_msil-cs-LC44" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L45" class="blob-num js-line-number js-blob-rnum" data-line-number="45"></td>
<td id="file-roslyn_msil-cs-LC45" class="blob-code blob-code-inner js-file-line">  // </td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L46" class="blob-num js-line-number js-blob-rnum" data-line-number="46"></td>
<td id="file-roslyn_msil-cs-LC46" class="blob-code blob-code-inner js-file-line">  .maxstack  8</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L47" class="blob-num js-line-number js-blob-rnum" data-line-number="47"></td>
<td id="file-roslyn_msil-cs-LC47" class="blob-code blob-code-inner js-file-line">  IL_0000:  ldarg.0</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L48" class="blob-num js-line-number js-blob-rnum" data-line-number="48"></td>
<td id="file-roslyn_msil-cs-LC48" class="blob-code blob-code-inner js-file-line">  IL_0001:  call instance void [mscorlib]</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L49" class="blob-num js-line-number js-blob-rnum" data-line-number="49"></td>
<td id="file-roslyn_msil-cs-LC49" class="blob-code blob-code-inner js-file-line">  System.Object::.ctor()</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L50" class="blob-num js-line-number js-blob-rnum" data-line-number="50"></td>
<td id="file-roslyn_msil-cs-LC50" class="blob-code blob-code-inner js-file-line">  IL_0006:  ret</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L51" class="blob-num js-line-number js-blob-rnum" data-line-number="51"></td>
<td id="file-roslyn_msil-cs-LC51" class="blob-code blob-code-inner js-file-line">  } // end of method Program::.ctor</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L52" class="blob-num js-line-number js-blob-rnum" data-line-number="52"></td>
<td id="file-roslyn_msil-cs-LC52" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L53" class="blob-num js-line-number js-blob-rnum" data-line-number="53"></td>
<td id="file-roslyn_msil-cs-LC53" class="blob-code blob-code-inner js-file-line">  } // end of class Program</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/dd7ace10bbca0668bf6337078d96483c/raw/73a63091d164236be813bb771a43ecac0fc52f27/roslyn_msil.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/dd7ace10bbca0668bf6337078d96483c#file-roslyn_msil-cs" class="Link--inTextBlock"><br />
          roslyn_msil.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>A bit more than the original source code, isn&#8217;t it? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Firstly there is a metadata instructions section which contains information about the assembly, execution framework’s version, types used in the code and external references. Next there&#8217;s the actual CIL code (equivalent to C# code presented above) listed.</p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-1" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1779348813" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-1" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<h2>Compiling CIL into native code</h2>
<p>We&#8217;ve already covered this step in details in <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">the previous post about Just-In-Time compilation</a>, which is just a bit more fancy name of this process <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Now you can see how and where it fits into .NET application&#8217;s execution model.</p>
<h3>Normal JIT compilation</h3>
<p>By default, JIT compilation is done in the place where &#8220;Normal JIT Compiler&#8221; is drawn on the schema below:</p>
<p><figure id="attachment_2920" aria-describedby="caption-attachment-2920" style="width: 580px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2920" data-permalink="https://www.codejourney.net/net-internals-10-application-execution-model/normaljit/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?fit=580%2C613&amp;ssl=1" data-orig-size="580,613" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NormalJit" data-image-description="" data-image-caption="&lt;p&gt;Normal JIT, source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?fit=580%2C613&amp;ssl=1" class="wp-image-2920 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?resize=580%2C613&#038;ssl=1" alt="" width="580" height="613" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?w=580&amp;ssl=1 580w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?resize=284%2C300&amp;ssl=1 284w" sizes="auto, (max-width: 580px) 100vw, 580px" /></a><figcaption id="caption-attachment-2920" class="wp-caption-text"><span style="font-size: 8pt;">Normal JIT, <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>IL instructions of a particular block of code, in the example diagram of a method <em>Foo()</em>, are JIT-compiled when the block is to be used for the first time. Then, this JIT-compiled code is stored as the JIT-ed equivalent of <em>Foo()</em> method’s code in the memory cache. Such native code is then executed and if the same block of code needs to be called again in the future, it will not be re-JIT-compiled, but instead the native code will be taken from the memory cache and executed again.</p>
<p>There&#8217;s a possibility to skip adding the native code into memory cache for future executions and it&#8217;s referred to as “Econo JIT Compilation”, however it&#8217;s not widely used and probably obsolete since few versions of .NET, so we won&#8217;t examine it here.</p>
<h3>Pre-JIT compilation</h3>
<p>The schema presented above changes a bit as soon as we want to use so called <em>Pre-JIT compilation</em>. <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/#AOT" target="_blank" rel="noopener">We mentioned it already</a> and we know that one of the techniques to allow pre-JIT (or <em>ahead-of-time</em>) compilation is using Native Image Generator (ngen.exe) which allows to transform CIL assemblies into native code files and to store them as a file on the disk (in the Native Image Cache). It allows to natively compile the whole assemblies – it doesn&#8217;t allow to compile only single methods as JIT compiler does.</p>
<p>&nbsp;</p>
<p>Refer to the new version of the schema presented below to see how the process changes with NGen.</p>
<p>&nbsp;</p>
<p><figure id="attachment_2924" aria-describedby="caption-attachment-2924" style="width: 509px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2924" data-permalink="https://www.codejourney.net/net-internals-10-application-execution-model/prejit/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?fit=509%2C614&amp;ssl=1" data-orig-size="509,614" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="PreJit" data-image-description="" data-image-caption="&lt;p&gt;Pre-JIT, source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?fit=509%2C614&amp;ssl=1" class="wp-image-2924 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?resize=509%2C614&#038;ssl=1" alt="" width="509" height="614" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?w=509&amp;ssl=1 509w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?resize=249%2C300&amp;ssl=1 249w" sizes="auto, (max-width: 509px) 100vw, 509px" /></a><figcaption id="caption-attachment-2924" class="wp-caption-text"><span style="font-size: 8pt;">Pre-JIT, <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>Normal and ahead-of-time CIL compilation modes provide different cons and pros, including:</p>
<ul>
<li>NGen delivers faster start-up time, especially in large applications used by many users in the same time, but requires more disk space and memory to store both the CIL and pre-compiled images,</li>
<li>JIT compilation at runtime can deliver faster code, because it targets the current platform of execution; NGen produces the native images with instructions that can be executed on all possible platforms, meaning it must use the oldest from currently used instructions sets to be backwards-compatible,</li>
<li>JIT is able to dynamically re-compile the code for a better performance depending on the execution conditions (e.g. by detecting a hot path in the executed code).</li>
</ul>
<p>Choosing one of the modes depends on your use case.</p>
<h2>Execution of the native code</h2>
<p>Finally, the code blocks are run by the CLR, which asks CPU to execute compiled instructions sets. If you&#8217;re interested in how CPU exactly works and executes the instructions, I recommend you watching <a href="https://www.youtube.com/watch?v=cNN_tTXABUA" target="_blank" rel="noopener">this YT video</a>.</p>
<h1>Summary</h1>
<p>We&#8217;ve seen today how the .NET applications are executed step-by-step, starting from source code (like C#) up to being actually executed by the processor.</p>
<p>I also encourage you to read &#8211; if you haven&#8217;t already &#8211; all the previous posts in the .NET Internals series. Just <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">click here</a> to see them all <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Let me know if you have any doubts or thoughts, I&#8217;m always open to your comments and opinions <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Especially the constructive ones pointing out some parts I omitted or didn&#8217;t describe precisely enough.</p>
<p>I hope it helped you learn something new <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/net-internals-10-application-execution-model/">[.NET Internals 10] Application execution model</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-10-application-execution-model/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2907</post-id>	</item>
		<item>
		<title>[.NET Internals 09] Just-In-Time (JIT) compilation</title>
		<link>https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/</link>
					<comments>https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 26 Sep 2018 18:10:35 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2883</guid>

					<description><![CDATA[<p>Have you ever heard the term JIT? It&#8217;s an acronym for Just-In-Time. JIT compiler is a tool which performs the JIT compilation, which is a crucial feature of .NET applications. Let&#8217;s say a few more words on it today 🙂 What makes managed applications portable? As we know from the previous posts published within the series, .NET&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/">[.NET Internals 09] Just-In-Time (JIT) compilation</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div>Have you ever heard the term <i>JIT</i>? It&#8217;s an acronym for Just-In-Time. <i>JIT compiler</i> is a tool which performs the <i>JIT compilation,</i> which is a crucial feature of .NET applications. Let&#8217;s say a few more words on it today <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<p><span id="more-2883"></span></p>
<div></div>
<h1>What makes managed applications portable?</h1>
<div>As we know from the previous posts <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener noreferrer">published within the series</a>, .NET Framework and CLR provide a lot of useful features for applications targeting the platform, such as <a href="http://internals" target="_blank" rel="noopener noreferrer">automatic memory management</a>. However, one of the main goals of managed runtimes&#8217; invention was to make implemented applications <em>portable</em>.</div>
<div></div>
<div></div>
<div>So what does it mean than an application is portable? It means that, first of all, it can be run on any kind of hardware. Ideally, it should also be software-agnostic (especially OS-agnostic). We can still observe this trend for instance by the fact that Microsoft created ans is actively developing a multi-platform <a href="https://github.com/dotnet/core" target="_blank" rel="noopener noreferrer">NET Core</a>.</div>
<div></div>
<div></div>
<div>Such portability not only makes the application possible to be launched on any hardware or software platform, but also releases developers from taking care about underlying low-level structures. For instance when working with <a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl" target="_blank" rel="noopener noreferrer">TPL</a>, the programmer normally doesn&#8217;t need to change his/her code taking into account the underlying hardware (e.g. number or architecture of CPUs). It&#8217;s the same for memory allocation (described in the previous posts) where many close-to-metal details differ based on operating system&#8217;s architecture (32/64 bit) &#8211; CLR handles it for us.</div>
<div></div>
<div></div>
<div>However, at some point, every application needs to be executed by the processor, which requires having a <i>machine code</i>  -assembly instructions understood and possible to be executed by the CPU. Depending on the OS&#8217;s or CPU&#8217;s architecture it&#8217;s sometimes necessary to use completely different CPU instructions sets in the assembly code. As you can guess, to make source code really portable it cannot be directly compiled to machine code. There&#8217;s something <em>intermediate</em> needed.</div>
<div></div>
<h1>Intermediate Language (IL)</h1>
<div>Because of the reasons described above, managed runtimes&#8217; programming languages source code (like C#, F# or Java) is not directly compiled to assembly language. Instead, it&#8217;s firstly compiled to an <i>intermediate language (IL)</i>.  CLR&#8217;s intermediate language is also referred to as MSIL (Microsoft Intermediate Language).</div>
<div></div>
<div></div>
<div>Compilation of source code into IL is performed by the particular language&#8217;s compiler. This is the process which happens when you build your app by pressing F6 in Visual Studio or <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe" target="_blank" rel="noopener noreferrer">using csc.exe to compile your code</a>.</div>
<div>Source code -&gt; IL compilation is done by the particular language&#8217;s compiler. For instance, C# code is compiled by <a href="https://github.com/dotnet/roslyn" target="_blank" rel="noopener noreferrer">Roslyn</a>. which is a C# language&#8217;s compiler:</div>
<div></div>
<div>
<div>
<p><figure id="attachment_2884" aria-describedby="caption-attachment-2884" style="width: 1302px" class="wp-caption alignleft"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2884" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/roslyn/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?fit=1302%2C186&amp;ssl=1" data-orig-size="1302,186" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Roslyn" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?fit=1024%2C146&amp;ssl=1" class="wp-image-2884 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=1140%2C163&#038;ssl=1" alt="" width="1140" height="163" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?w=1302&amp;ssl=1 1302w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=300%2C43&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=768%2C110&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=1024%2C146&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=720%2C103&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></a><figcaption id="caption-attachment-2884" class="wp-caption-text"><span style="font-size: 8pt;">Visual Studio&#8217;s build &#8211; Roslyn</span></figcaption></figure></p>
</div>
</div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<h2>Viewing MSIL</h2>
<div>In order to see the MSIL code contained in the compiled EXE/DLL files (like I showed you e.g. <a href="https://www.codejourney.net/2018/09/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/" target="_blank" rel="noopener noreferrer">here</a> and <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing/" target="_blank" rel="noopener noreferrer">here</a>), you can use <a href="https://marketplace.visualstudio.com/items?itemName=SharpDevelopTeam.ILSpy" target="_blank" rel="noopener noreferrer">ILSpy Visual Studio extension</a>, which, when installed, adds a menu option in Visual Studio (Tools -&gt; ILSpy), where you can open any compiled file and view the IL code of contained objects:</div>
<div>
<p><figure id="attachment_2886" aria-describedby="caption-attachment-2886" style="width: 989px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2886" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/ilspy_il/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?fit=989%2C348&amp;ssl=1" data-orig-size="989,348" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ILSpy_IL" data-image-description="" data-image-caption="&lt;p&gt;ILSpy &amp;#8211; MSIL code&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?fit=989%2C348&amp;ssl=1" class="wp-image-2886 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=989%2C348&#038;ssl=1" alt="" width="989" height="348" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?w=989&amp;ssl=1 989w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=300%2C106&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=768%2C270&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=720%2C253&amp;ssl=1 720w" sizes="auto, (max-width: 989px) 100vw, 989px" /></a><figcaption id="caption-attachment-2886" class="wp-caption-text"><span style="font-size: 8pt;">ILSpy &#8211; MSIL code</span></figcaption></figure></p>
</div>
<div>
<div>What is actually compiled into IL code? For now we can say that the most important are methods (grouped into classes, namespaces etc. of course). There are also many other things compiled (even more than you would expect by looking at your source code), but we will focus on the methods for now.</p>
</div>
<div></div>
<div>OK, so we have the IL code now, but it cannot be understood by the CPU yet. How and when is it then compiled to assembly code?</div>
</div>
<h1>Just-In-Time (JIT) compilation</h1>
<h2>How Toyota brought us JIT?</h2>
<div>Let&#8217;s start by some historical background <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> In the early 1960s, Japanese engineers at Toyota had to reorganize their warehouse management, because they had very high storage costs &#8211; delivery of the parts from suppliers took a lot of time, because they ordered a lot in advance. Every delivery had to be handled by someone, so they needed a lot of employees. Ordered parts were stored in the warehouses for a long time, required a lot or storage space and maintenance.</div>
<div></div>
<div></div>
<div>In order to minimize the costs, they invented a <i>just-in-time manufacturing</i> (also known as T<i>oyota Production System</i>). Its main principle was to <b>order goods from the suppliers only when the minimal level of stocks on the warehouse was reached</b>. In effect, the goods were delivered <i>just in time</i> they were needed on the production line. It minimized the number of deliveries (and warehouse employees) and in the same time didn&#8217;t require that much storage space as before.</div>
<div></div>
<div>The whole idea can be imagined as the following flows order:</div>
<div>
<p><figure id="attachment_2889" aria-describedby="caption-attachment-2889" style="width: 728px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2889" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/toyota_jit/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?fit=728%2C546&amp;ssl=1" data-orig-size="728,546" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Toyota_JIT" data-image-description="" data-image-caption="&lt;p&gt;Toyota Production System (JIT), source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?fit=728%2C546&amp;ssl=1" class="wp-image-2889 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?resize=728%2C546&#038;ssl=1" alt="" width="728" height="546" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?w=728&amp;ssl=1 728w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?resize=300%2C225&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?resize=720%2C540&amp;ssl=1 720w" sizes="auto, (max-width: 728px) 100vw, 728px" /></a><figcaption id="caption-attachment-2889" class="wp-caption-text"><span style="font-size: 8pt;">Toyota Production System (JIT), <a href="https://www.slideshare.net/nsjidnjkj/toyota-5458336" target="_blank" rel="noopener noreferrer">source</a></span></figcaption></figure></p>
</div>
<h2>JIT compiler</h2>
<div>
<div>Following Toyota&#8217;s success <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , CLR creators introduced a <i>just-in-time (JIT)</i> <i>compiler</i> into the framework. Its role is to <b>compile intermediate language code into assembly language</b> according to hardware and operating system&#8217;s characteristics (depending on the machine on which the code is being JIT-compiled). Unlike unmanaged languages, in which the source code is compiled into machine language prior to program&#8217;s execution, IL is (by default) compiled to CPU instructions <b>at runtime</b>. That&#8217;s how .NET engineers made the machine code delivered on time to the CPU.</div>
<div></div>
</div>
<div>
<div></div>
<div>JIT compiler is a part of CLR (similarly to <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener noreferrer">garbage collector</a>). To make things simple, it can be said that JIT compiles a particular method&#8217;s source code as soon as this method is called for the first time. Of course, it takes into account the hardware, e.g. the CPU type and its instructions set to produce correct assembly code. Such machine code is then saved in the cache and re-used every time the same method is called again within the same application&#8217;s execution. It means that the parts of the code which are not used (called) during the program&#8217;s execution may not be JIT-compiled at all.</div>
<div></div>
<div>Just-In-Time compilation is actually a combination of two approaches: ahead-of-time compilation and interpretation, mixing advantages and disadvantages of both. However, compiling IL code into assembly one at runtime allows for several interesting features like dynamic typing (ability to retrieve the actual object&#8217;s type at program&#8217;s execution). That&#8217;s why JIT compilation is often treated as a form of <i>dynamic compilation</i>.</div>
<div></div>
<div>Another advantage of having JIT compilation is that the source code we write is &#8220;further from the hardware&#8221;, so it can be made more readable and human-friendly, whereas the metal-touching stuff is &#8220;hidden&#8221; in the IL (kudos to MSIL developers!) <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<div></div>
</div>
<div>JIT compilation has also some cost &#8211; naturally it requires time to compile the code at runtime. On the other hand, various CPU units may have different powerful instructions sets or processing units that may be used in the assembly produced by the JIT, which wouldn&#8217;t be the case in ahead-of-time compilation (without any special tuning).</div>
<h2 id="AOT">Can we still compile ahead-of-time?</h2>
<div>If you really don&#8217;t like JIT (why would you?), there are ways to pre-JIT-compile your EXE/DLLs prior to an application&#8217;s execution. This is called <em>Pre-JIT compilation</em>. One of the reasons for that can be that a lot of users will run our application from the same EXE/DLL files, which would normally make JIT-compiling the IL for each user separately. In such case it may be relevant to pre-JIT-compile our application&#8217;s files for performance and memory usage reasons. It can be done using <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/ngen-exe-native-image-generator" target="_blank" rel="noopener noreferrer">NGen</a> (for all versions of .NET) or <a href="https://docs.microsoft.com/en-us/dotnet/framework/net-native/" target="_blank" rel="noopener noreferrer">.NET Native</a> (for .NET apps targeting Windows 10). We will not be describing these tools in details today (you can find more information on the Internet).</div>
<h1>Summary</h1>
<div>JIT compilation is a process of compiling an intermediate language (IL) into native (machine) code at runtime. It provides the portability of managed applications. It&#8217;s a very important concept to understand, as it&#8217;s introduced in a lot of currently used programming frameworks like Java, .NET and Android.</p>
</div>
<div>In one of the next posts we&#8217;ll dig into application execution model in .NET Framework, where we&#8217;ll see when and how exactly the JIT compilation process fits into the whole C#-&gt;CPU journey <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>
<div>Finally, as always, remember that:</div>
<div>
<p><figure id="attachment_2892" aria-describedby="caption-attachment-2892" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2892" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/george_meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?fit=630%2C630&amp;ssl=1" data-orig-size="630,630" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="george_meme" data-image-description="" data-image-caption="&lt;p&gt;Source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?fit=630%2C630&amp;ssl=1" class="wp-image-2892 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?resize=300%2C300&#038;ssl=1" alt="" width="300" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?resize=300%2C300&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?resize=150%2C150&amp;ssl=1 150w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?w=630&amp;ssl=1 630w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2892" class="wp-caption-text"><a href="https://www.teepublic.com/t-shirt/2228544-funny-george-washington-history-meme" target="_blank" rel="noopener noreferrer"><span style="font-size: 8pt;">Source</span></a></figcaption></figure></p>
<p>so if you have your own opinion on JIT or any other remarks, <span style="text-decoration: underline;"><strong>don&#8217;t bother and share it in the comments</strong></span>! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>
<p>The post <a href="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/">[.NET Internals 09] Just-In-Time (JIT) compilation</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2883</post-id>	</item>
		<item>
		<title>[.NET Internals 08] What about Large Object Heap (LOH)?</title>
		<link>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/</link>
					<comments>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 13:00:58 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2812</guid>

					<description><![CDATA[<p>So far within the .NET Internals series we focused on Small Object Heap (SOH). We know, for instance, that the LOH is not compacted (by default) during garbage collection. So how is it actually handled by the GC? (De)allocating objects on LOH As we know from the second post, during allocating the memory only objects&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/">[.NET Internals 08] What about Large Object Heap (LOH)?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So far within the <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a> we focused on Small Object Heap (SOH). We know, for instance, that the <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">LOH is not compacted (by default) during garbage collection</a>. So how is it actually handled by the GC?<br />
<span id="more-2812"></span></p>
<h1>(De)allocating objects on LOH</h1>
<p>As we know from the <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">second post</a>, during allocating the memory only objects of size greater than 85,000 bytes are placed on LOH. There are also some exceptions, like arrays of <span style="color: #ff6600; font-family: terminal, monaco, monospace;">double</span> which are put on LOH (in 32-bit architectures only) as soon as they reach 1000 (or more) elements (not something around 10626 elements as could be expected). This is quite important to know to be aware what kind of objects have impact on heap fragmentation (more details below).</p>
<p>&nbsp;</p>
<p>So we know when the objects are allocated on LOH, but when are they deallocated?</p>
<p>LOH is collected in the same time as the generation 2 collection occurs. It can be triggered if memory threshold for either gen 2 or LOH is exceeded. Conditions for garbage collection can be found <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">in this post</a>.</p>
<p>That&#8217;s why keeping large LOH may affect the GC&#8217;s &#8211; and the whole application&#8217;s &#8211; performance.</p>
<h1>Garbage collection on LOH</h1>
<h2>LOH fragmentation</h2>
<p>The reason why Large Object Heap is not compacted (by default) is because it&#8217;s used to store big objects (&gt;85,000 bytes). Copying such amounts of data would seriously incur the performance of garbage collection process.</p>
<p>Anyway, memory of objects allocated on the LOH is reclaimed so it may eventually become fragmented:</p>
<p><figure id="attachment_2546" aria-describedby="caption-attachment-2546" style="width: 138px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2546" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/virtualmemoryfragmentation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" data-orig-size="138,305" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="VirtualMemoryFragmentation" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" class="wp-image-2546 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=138%2C305&#038;ssl=1" alt="" width="138" height="305" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?w=138&amp;ssl=1 138w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=136%2C300&amp;ssl=1 136w" sizes="auto, (max-width: 138px) 100vw, 138px" /></a><figcaption id="caption-attachment-2546" class="wp-caption-text"><span style="font-size: 8pt;">LOH fragmentation</span></figcaption></figure></p>
<p>We&#8217;ll see below how, but <strong>.NET keeps track of &#8220;Free space&#8221; memory blocks to know which chunks are available for new allocations on LOH</strong>. When allocating it looks for a block large enough to store the whole object.</p>
<p>&nbsp;</p>
<p>However, imagine that there are 2 free space blocks next to each other. Both were marked free, but they represented different objects (maybe they were next to each other on the heap because one referenced the other). What do you think GC will do? Will it treat them as two separate free memory blocks, making less chances for the next allocated object to fit into one of them?</p>
<p>Fortunately not. <strong>GC has an optimization introduced which makes such adjacent free memory chunks &#8220;merged&#8221; together</strong>:</p>
<p><figure id="attachment_2813" aria-describedby="caption-attachment-2813" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2813" data-permalink="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/loh_holesmerging/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?fit=534%2C455&amp;ssl=1" data-orig-size="534,455" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="LOH_HolesMerging" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?fit=534%2C455&amp;ssl=1" class="wp-image-2813 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?resize=300%2C256&#038;ssl=1" alt="" width="300" height="256" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?resize=300%2C256&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?w=534&amp;ssl=1 534w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2813" class="wp-caption-text"><span style="font-size: 8pt;">Free memory chunks &#8220;merged&#8221; on LOH</span></figcaption></figure></p>
<p>How does GC do it? Let&#8217;s see in more details.</p>
<h2>Free memory representation on LOH</h2>
<p>Instead of compacting Large Object Heap, garbage collector keeps the address ranges of not used large objects in a Free Space Table:</p>
<p><figure id="attachment_2815" aria-describedby="caption-attachment-2815" style="width: 900px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2815" data-permalink="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/freespacetable/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?fit=900%2C442&amp;ssl=1" data-orig-size="900,442" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FreeSpaceTable" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?fit=900%2C442&amp;ssl=1" class="wp-image-2815 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=900%2C442&#038;ssl=1" alt="" width="900" height="442" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?w=900&amp;ssl=1 900w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=300%2C147&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=768%2C377&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=720%2C354&amp;ssl=1 720w" sizes="auto, (max-width: 900px) 100vw, 900px" /></a><figcaption id="caption-attachment-2815" class="wp-caption-text"><span style="font-size: 8pt;">Free Space Table, <a href="https://www.red-gate.com/library/under-the-hood-of-net-memory-management" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>As you can see on the figure above, as soon as gen 2 collection run, address ranges of two unused objects were just added to the Free Space Table.</p>
<p>Now you can see that &#8220;merging&#8221; two adjacent free memory chunks is just a simple addition operation (or modification of one number in the table).</p>
<h2>Allocating memory on LOH</h2>
<p>As soon as a new large (&gt;85,000 bytes or applicable array) object is to be allocated on the managed heap, GC looks for a single &#8220;Free Space&#8221; block to hold it. However, it&#8217;s rather unlikely that the particular object&#8217;s size will fit into one of the free memory chunks. In that case, a new object will be allocated on the top of the heap (just after &#8216;Object D&#8217; on the figure above).</p>
<p>&nbsp;</p>
<p>It may happen that the memory obtained from the operating system for LOH is already used (<a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">read here</a> for more info about memory). Garbage collector then asks the operating system for more memory segments to be acquired for LOH. If it fails, gen 2 collection is triggered hoping that some memory blocks will be freed and then the allocation will be possible.</p>
<p>&nbsp;</p>
<p>Let&#8217;s now think about it for a while. We said previously that LOH collection triggers gen 2 collection. So trying to clean-up the Large Object Heap every time an allocation on it is made would be a potential performance killer.</p>
<p>&nbsp;</p>
<p>How does GC solve this issue? Well, in fact, after a lot of optimizations introduced to LOH management in .NET 4.5, the GC takes the following actions in order to make a new allocation of a large object:</p>
<ul>
<li>firstly, the GC tries to allocate new objects into one of the free space &#8220;holes&#8221; on the LOH (it&#8217;s quite simple to calculate whether any chunk is large enough to store the object knowing ranges of free space blocks from the Free Space Table).</li>
<li>if the above fails &#8211; garbage collector prefers to allocate new large objects at the end of the heap. Even though it may involve asking the OS for more memory segments, it&#8217;s been found to be easier and less consuming operation than performing full GC hoping to free some memory chunks on the LOH first.</li>
<li>only if the above fails (LOH cannot be &#8220;extended&#8221;) &#8211; GC triggers gen 2 collection hoping to free some additional space that could be used for a new allocation.</li>
</ul>
<p>What&#8217;s worth noticing is that <strong>this actions order seems to be good for performance, but can sometimes be a reason of memory fragmentation</strong>.</p>
<h2>Manual LOH compaction</h2>
<p>As you should already know from <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">the previous article</a>, LOH can be compacted programmatically, by setting the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.gcsettings.largeobjectheapcompactionmode?view=netframework-4.7.2" target="_blank" rel="noopener">GCSettings.LargeObjectHeapCompactionMode</a> property. The simplest way to force LOH compaction is as the following snippet presents:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91845646" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-loh_manual_compaction-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="LOH_manual_compaction.cs content, created by dsibinski on 04:58PM on September 11, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="LOH_manual_compaction.cs">
<tr>
<td id="file-loh_manual_compaction-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-loh_manual_compaction-cs-LC1" class="blob-code blob-code-inner js-file-line">  GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;</td>
</tr>
<tr>
<td id="file-loh_manual_compaction-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-loh_manual_compaction-cs-LC2" class="blob-code blob-code-inner js-file-line">  GC.Collect();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c41faa4201d987b17102f0229dfa20cc/raw/4b9004f1d32a3576ff40271590ed0e3cc82130b2/LOH_manual_compaction.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c41faa4201d987b17102f0229dfa20cc#file-loh_manual_compaction-cs" class="Link--inTextBlock"><br />
          LOH_manual_compaction.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>There might be some niche cases in which LOH compaction may be useful. More details and discussions can be found for example <a href="https://stackoverflow.com/questions/20035550/large-object-heap-compaction-when-is-it-good" target="_blank" rel="noopener">here</a>.</p>
<h2>Best practices working with LOH objects</h2>
<p>We can try to simply design our applications to use the less possible number of large objects, but let&#8217;s not exaggerate. We are living in a world where 8GBs of 2133MHz RAM costs sometimes less than 100$, so the memory is generally cheap <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>In principle, the rule seems to be simple: <strong>large objects we allocate should be reused (e.g. cached) as much as possible</strong>.</p>
<p>We should just keep in mind that allocation of large objects can be costly, because of a need to perform gen 2 collection in some cases before the object is allocated.</p>
<p>An example of potentially problematic large object can be a <a href="https://msdn.microsoft.com/en-us/library/ms972976.aspx" target="_blank" rel="noopener">ViewState</a> used in ASP.NET applications, size of which can easily exceed 85K. There are some good articles explaining how to not stupidly incur ASP.NET app&#8217;s performance using it, for instance <a href="https://dzone.com/articles/optimize-aspnet-performance-with-view-state-cachin" target="_blank" rel="noopener">this one</a>.</p>
<p>There are also a lot of tools which can be used to measure the memory state and performance of our applications (also its internal mechanisms like garbage collection, heaps compaction etc.) which we&#8217;ll surely cover in one of the next posts within <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">the series</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Summary</h1>
<p>Today we examined &#8211; previously a bit forgotten &#8211; Large Object Heap. We saw how the information about free memory blocks on it is stored by .NET Framework and how new objects are allocated on it.</p>
<p>&nbsp;</p>
<p>I think it&#8217;s one of the next internal concepts of .NET worth knowing and understanding, even though in the common scenarios and business applications you probably won&#8217;t get into troubles with LOH. However, it may be practical and useful to know when working with some more memory-demanding applications like games.</p>
<p>I hope this post clarifies some LOH topics for you.</p>
<p><span style="text-decoration: underline;">Let me know if there are any topics you&#8217;d be interested in reading about</span>. I&#8217;m here to provide some value to you, so I&#8217;m open for your criticism and suggestions <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Stay tuned!</p>
<p>&nbsp;</p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-2" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1779348813" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-2" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/">[.NET Internals 08] What about Large Object Heap (LOH)?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2812</post-id>	</item>
		<item>
		<title>[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</title>
		<link>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/</link>
					<comments>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 05 Sep 2018 13:00:22 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2779</guid>

					<description><![CDATA[<p>Today we&#8217;re going to see how unmanaged resources are handled by .NET, what are finalization and fReachable queues and what&#8217;s the garbage collector&#8217;s role in it. We&#8217;ll also get to know what is a dispose pattern and see how to implement it. Unmanaged resources and finalizers First of all we should all get familiar with what&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/">[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today we&#8217;re going to see how unmanaged resources are handled by .NET, what are <em>finalization</em> and <em>fReachable queues</em> and what&#8217;s the garbage collector&#8217;s role in it. We&#8217;ll also get to know what is a <em>dispose pattern</em> and see how to implement it.<br />
<span id="more-2779"></span></p>
<h1>Unmanaged resources and finalizers</h1>
<p>First of all we should all get familiar with what <em>unmanaged resources</em> are. These ones can be files or folders on the disk, database connections, GUI elements or network resources. You can also think of them as some external elements we need to interact with in our applications through some protocol (e.g. database queries or file system manipulation methods). They&#8217;re called <em>unmanaged</em> not without a reason &#8211; <strong>any unmanaged resources accessed from .NET code will not be automatically cleaned by the garbage collector</strong>. That&#8217;s how they are <em>not(un)managed</em>.</p>
<p>Maybe you&#8217;ve heard about <a href="https://en.cppreference.com/w/cpp/language/destructor" target="_blank" rel="noopener">destructors in C++</a> &#8211; remember methods called after class&#8217;s name (like its constructor) starting with &#8216;~&#8217; character? This also exists in .NET, but it&#8217;s not what you&#8217;d expect from C++. In .NET, such methods are referred to as <strong>finalizers</strong>.</p>
<h2>Finalizers and destructors in .NET</h2>
<p>Nonetheless, you can define a finalizer in your class in one of the following ways:</p>
<p>&nbsp;</p>
<p><strong> Using &#8220;destructor-like&#8221; syntax:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91695157" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-destructor_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Destructor_Example.cs content, created by dsibinski on 07:36PM on September 03, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Destructor_Example.cs">
<tr>
<td id="file-destructor_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-destructor_example-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace UnmanagedResourcesTests</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-destructor_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-destructor_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    class MyTestClass</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-destructor_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-destructor_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        ~MyTestClass()</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-destructor_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-destructor_example-cs-LC7" class="blob-code blob-code-inner js-file-line">            Console.WriteLine(&quot;Finalizing my object!&quot;);</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-destructor_example-cs-LC8" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-destructor_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-destructor_example-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c50e995d8697d7b27412789647abb372/raw/da9dc7058cfc1b1ccb57b878d2a4def0760ed953/Destructor_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c50e995d8697d7b27412789647abb372#file-destructor_example-cs" class="Link--inTextBlock"><br />
          Destructor_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><strong>Using Finalize() method:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91695262" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-finalizer_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Finalizer_Example.cs content, created by dsibinski on 07:44PM on September 03, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Finalizer_Example.cs">
<tr>
<td id="file-finalizer_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-finalizer_example-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace UnmanagedResourcesTests</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-finalizer_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-finalizer_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    class MyTestClass</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-finalizer_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-finalizer_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        void Finalize()</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-finalizer_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-finalizer_example-cs-LC7" class="blob-code blob-code-inner js-file-line">            Console.WriteLine(&quot;Finalizing my object!&quot;);</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-finalizer_example-cs-LC8" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-finalizer_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-finalizer_example-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/a5becab104ef57f2c8c35d8f9c66b672/raw/c1b3c742398d331530cf161a2aad242a4b65dcad/Finalizer_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/a5becab104ef57f2c8c35d8f9c66b672#file-finalizer_example-cs" class="Link--inTextBlock"><br />
          Finalizer_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>If you examine the IL code of both versions, it turns out that the <strong>destructor can be seen as a syntax sugar for the finalizer</strong>. In fact, the <span style="color: #ff6600;">~MyTestClass()</span> method is translated into <span style="color: #ff6600;">Finalize()</span> method:</p>
<p><figure id="attachment_2781" aria-describedby="caption-attachment-2781" style="width: 698px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2781" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizeil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?fit=698%2C648&amp;ssl=1" data-orig-size="698,648" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizeIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?fit=698%2C648&amp;ssl=1" class="wp-image-2781 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?resize=698%2C648&#038;ssl=1" alt="" width="698" height="648" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?w=698&amp;ssl=1 698w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?resize=300%2C279&amp;ssl=1 300w" sizes="auto, (max-width: 698px) 100vw, 698px" /></a><figcaption id="caption-attachment-2781" class="wp-caption-text"><span style="font-size: 8pt;">Destructor translated into Finalize() in IL</span></figcaption></figure></p>
<p>The only difference is that &#8211; as you can see on the IL above &#8211; <span style="color: #ff6600;">Finalize()</span> method created by the compiler from the destructor is implicitly calling the <span style="color: #ff6600;">Finalize()</span> method on the base class of the object (you can see it in the <span style="color: #ff6600;">finally</span> block in the IL generated). So in case of using a destructor-like syntax, we are actually creating a finalizer by overriding <span style="color: #ff6600;">Finalize()</span> method, whereas when implementing a <span style="color: #ff6600;">Finalize()</span> method directly we do it as we&#8217;d use the <span style="color: #ff6600;">new</span> keyword (hiding base class&#8217;s implementation of <span style="color: #ff6600;">Finalize()</span> method).</p>
<h2>Will GC call the finalizer for me?</h2>
<p>As you may know, finalizers methods are normally used to clean-up some unmanaged resources (e.g. to release a file handle or database connection). You may think that as soon as your object is ready to be collected (nothing references it anymore), garbage collector will firstly call the finalizer (to ensure everything is cleaned up) and then reclaim the memory used by the object.</p>
<p><strong>Unfortunately not</strong>. If you think about it one more time &#8211; GC cannot know what&#8217;s inside your <span style="color: #ff6600;">Finalize()</span> method. You can put there the code which downloads the whole Internet just like that:</p>
<p><figure id="attachment_2784" aria-describedby="caption-attachment-2784" style="width: 490px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2784" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/wholeinternet/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?fit=490%2C260&amp;ssl=1" data-orig-size="490,260" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="WholeInternet" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?fit=490%2C260&amp;ssl=1" class="wp-image-2784 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?resize=490%2C260&#038;ssl=1" alt="" width="490" height="260" /></a><figcaption id="caption-attachment-2784" class="wp-caption-text"><a href="https://knowyourmeme.com/photos/53057-the-last-page-of-the-internet" target="_blank" rel="noopener"><span style="font-size: 8pt;">Source</span></a></figcaption></figure></p>
<p>&#8230; and even though we have nowadays a bit faster bandwidths than the one from the gif <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , you can clearly see it wouldn&#8217;t be a good idea to block garbage collection because of some costly process being executed before the memory for the object is reclaimed.</p>
<p>In order to avoid the above-described scenario, which would slow down the GC&#8217;s work significantly, .NET contributors decided that the <strong>finalizers on the objects are called periodically on a separate thread, completely independently from the GC</strong>.</p>
<p>This way the main GC thread is not blocked. However, it adds a bit of complexity to the garbage collection process &#8211; continue reading for more details.</p>
<h1>Finalization mechanism</h1>
<p>As we said in <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">one of the previous posts</a>, one of the various sources of references to objects in our .NET application (GC roots) are &#8220;objects finalization references&#8221;. Let&#8217;s now make this mysterious term clear.</p>
<p>&nbsp;</p>
<p>In order to prevent having a finalizable object (containing finalizer method) reclaimed before its <span style="color: #ff6600;">Finalize()</span> method is called (which happens independently from the GC as you already know), there&#8217;s a separate references list called <strong>finalization queue </strong>maintained by the GC. As soon as memory for a new finalizable object is allocated, a reference to it is also put on the finalization queue, which becomes a <em>finalization root</em> for this object (it&#8217;s not the same kind of root as &#8220;normal&#8221; GC roots &#8211; it&#8217;s treated a bit more differently).</p>
<p>The diagram below presents the memory state just after few new objects were allocated on the managed heap.</p>
<p><figure id="attachment_2790" aria-describedby="caption-attachment-2790" style="width: 504px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2790" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizationfreachablequeue1-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?fit=504%2C398&amp;ssl=1" data-orig-size="504,398" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizationFreachableQueue1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?fit=504%2C398&amp;ssl=1" class="wp-image-2790 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?resize=504%2C398&#038;ssl=1" alt="" width="504" height="398" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?w=504&amp;ssl=1 504w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?resize=300%2C237&amp;ssl=1 300w" sizes="auto, (max-width: 504px) 100vw, 504px" /></a><figcaption id="caption-attachment-2790" class="wp-caption-text"><span style="font-size: 8pt;">Finalization and fReachable queues before GC, <a href="https://www.dotnettricks.com/learn/netframework/net-garbage-collection-and-finalization-queue" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>As you can see, objects <em>ob2</em>, <em>ob3</em>, <em>ob5</em>, <em>ob6</em> and <em>ob10 </em>are all placed on the finalization queue, which means all of them contain <span style="color: #ff6600;">Finalize()</span> method.</p>
<p>Within these objects, <em>ob2</em> and <em>ob5</em> don&#8217;t have any references (roots) &#8211; it&#8217;s visible on the left side (heap). It means that these two objects are not used (are not referenced by anything) so they&#8217;re ready to be garbage collected. However, each of them contains a finalization root on the finalization queue.</p>
<p>As soon as the next garbage collection occurs, <em>ob2</em> and <em>ob5</em> cannot be reclaimed straightaway, as there&#8217;s a <span style="color: #ff6600;">Finalize()</span> method to be called on them first. Instead, when GC examines these two objects, it sees that they are not referenced from &#8220;normal&#8221; roots, but they have finalization references on the finalization queue. If that&#8217;s the case, GC moves finalization reference to another data structure called <strong>fReachable queue </strong>(also visible on the diagram above).</p>
<p>After, both queues and the heap look as follows:</p>
<p><figure id="attachment_2791" aria-describedby="caption-attachment-2791" style="width: 496px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2791" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizationfreachablequeue2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?fit=496%2C386&amp;ssl=1" data-orig-size="496,386" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizationFreachableQueue2" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?fit=496%2C386&amp;ssl=1" class="wp-image-2791 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?resize=496%2C386&#038;ssl=1" alt="" width="496" height="386" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?w=496&amp;ssl=1 496w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?resize=300%2C233&amp;ssl=1 300w" sizes="auto, (max-width: 496px) 100vw, 496px" /></a><figcaption id="caption-attachment-2791" class="wp-caption-text"><span style="font-size: 8pt;">Finalization and fReachable queues after GC, <a href="https://www.dotnettricks.com/learn/netframework/net-garbage-collection-and-finalization-queue" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>That&#8217;s what I meant by stating that finalization roots are &#8220;special&#8221; kind of GC roots. Apart from that, <em>ob2</em> and <em>ob5</em> are still seen as &#8220;rooted&#8221; (as still being referenced) and because of that are not reclaimed by the GC. In that moment, standard <a href="https://www.codejourney.net/2018/08/net-internals-06-generational-garbage-collection/" target="_blank" rel="noopener">generational GC rules</a> apply, so if the collection below was a gen 1 collection, both objects will be promoted to gen 2.</p>
<p>Periodically, the finalization runs on a separate thread exploring the fReachable queue and calling <span style="color: #ff6600;">Finalize()</span> method on each object referenced from it. Then it removes the reference to this object from the queue. At this moment, finalizable object becomes rootless and can be reclaimed in the next garbage collection cycle.</p>
<h1>Dispose for the rescue</h1>
<p>In order to unify usage of finalizers and allow developers to correctly free their resources without unnecessarily prolonging their objects&#8217; lifetime (as you saw above, finalizable objects stay uncollected for at least 1 more GC round than &#8220;normal&#8221; objects), programmer can (and should) implement a <strong><em>dispose pattern</em></strong>. The purpose of it is <strong>to allow the developer to free unmanaged resources &#8220;manually&#8221; as soon as they are not needed anymore</strong>.</p>
<p>&nbsp;</p>
<p>The framework also provides a <span style="color: #ff6600;"><a style="color: #ff6600;" href="https://docs.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize?view=netframework-4.7.2" target="_blank" rel="noopener">GC.SuppressFinalize</a></span> method which tells GC that the object has been manually disposed and no more finalization is necessary. As soon as it&#8217;s called, the object reference is removed from finalization/fReachable queue. The goal is to prevent finalizing the object twice.</p>
<h2>IDisposable</h2>
<p>.NET Framework provides a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=netframework-4.7.2" target="_blank" rel="noopener">System.IDisposable</a> interface which should be implemented by a class which works with unmanaged resources.</p>
<p>Sample implementation of dispose pattern can look as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91713758" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_example.cs content, created by dsibinski on 06:58PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_example.cs">
<tr>
<td id="file-dispose_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_example-cs-LC1" class="blob-code blob-code-inner js-file-line">public class UnmanagedClass : IDisposable</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    public void Dispose()</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-dispose_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-dispose_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        CleanUp(true);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-dispose_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        GC.SuppressFinalize(this);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-dispose_example-cs-LC7" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-dispose_example-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-dispose_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    private void CleanUp(bool disposing)</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-dispose_example-cs-LC10" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-dispose_example-cs-LC11" class="blob-code blob-code-inner js-file-line">        if (disposing)</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-dispose_example-cs-LC12" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-dispose_example-cs-LC13" class="blob-code blob-code-inner js-file-line">            // any thread-specific cleanup code</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-dispose_example-cs-LC14" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-dispose_example-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-dispose_example-cs-LC16" class="blob-code blob-code-inner js-file-line">        // cleaning unmanaged resources here</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-dispose_example-cs-LC17" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-dispose_example-cs-LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-dispose_example-cs-LC19" class="blob-code blob-code-inner js-file-line">    public void Finalize()</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-dispose_example-cs-LC20" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-dispose_example-cs-LC21" class="blob-code blob-code-inner js-file-line">        CleanUp(false);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-dispose_example-cs-LC22" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-dispose_example-cs-LC23" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/2c51fc4c0f2df3ec9c4c69efd6f3bb7b/raw/125032117302184cabb58e8d8a0ca9a96b80405b/Dispose_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/2c51fc4c0f2df3ec9c4c69efd6f3bb7b#file-dispose_example-cs" class="Link--inTextBlock"><br />
          Dispose_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Implementing <span style="color: #ff6600;">IDisposable</span> interface only forces us to add <span style="color: #ff6600;">Dispose()</span> method. Inside, we perform the resources clean-up and call <span style="color: #ff6600;">GC.SuppressFinalize(this)</span> to mark our object as finalized. We also implemented a separate method, in the example called <span style="color: #ff6600;">CleanUp(bool disposing)</span>, which performs the actual releasing of unmanaged resources. But why do we need this <span style="color: #ff6600;">bool disposing</span> parameter?</p>
<p>&nbsp;</p>
<p>It may be important to differentiate when the resources cleanup is called directly from code (we&#8217;ll see how it can be done in the next section) or by the finalization thread. As you already know, finalization is executed periodically <strong>on a separate thread</strong>. It means that if our <span style="color: #ff6600;">UnmanagedClass</span> needs any thread-specific resources cleanup, it&#8217;s not a good idea to execute it on totally independent, finalization thread, which is out-of-context at that moment.</p>
<p>That&#8217;s why we added a boolean parameter to the <span style="color: #ff6600;">CleanUp</span> method, which will be set to &#8220;true&#8221; as soon as <span style="color: #ff6600;">Dispose()</span> method is called directly from code. In that case we know that we can execute thread-specific cleanup code.</p>
<p>Additionally, we implemented the <span style="color: #ff6600;">Finalize()</span> method, which also calls <span style="color: #ff6600;">CleanUp()</span>, but passing &#8220;false&#8221; parameter&#8217;s value. In that case, as the finalization thread is out-of-context, we shouldn&#8217;t execute thread-specific cleanup code. We should treat <span style="color: #ff6600;">Finalize()</span> method as a last resort in case <span style="color: #ff6600;">Dispose()</span> has not been called because of some reason.</p>
<p>You can also check <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose" target="_blank" rel="noopener">Microsoft dosc</a> to see what&#8217;s their recommendation on implementing IDisposable interface.</p>
<h2>Using statement</h2>
<p>As mentioned above, the programmer can explicitly call <span style="color: #ff6600;">Dispose()</span> method on the class:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91714024" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_manually-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_manually.cs content, created by dsibinski on 07:10PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_manually.cs">
<tr>
<td id="file-dispose_manually-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_manually-cs-LC1" class="blob-code blob-code-inner js-file-line">  UnmanagedClass myClass = new UnmanagedClass();</td>
</tr>
<tr>
<td id="file-dispose_manually-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_manually-cs-LC2" class="blob-code blob-code-inner js-file-line">  // working with the instance&#8230;</td>
</tr>
<tr>
<td id="file-dispose_manually-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_manually-cs-LC3" class="blob-code blob-code-inner js-file-line">  myClass.Dispose();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/e8d933cf16b9a09aff19a97de6fc32ce/raw/78b5351e222055e3124a0eae88ad4b75fd0b6b56/Dispose_manually.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e8d933cf16b9a09aff19a97de6fc32ce#file-dispose_manually-cs" class="Link--inTextBlock"><br />
          Dispose_manually.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>but there&#8217;s another &#8211; and preferred &#8211; way: wrapping usage of the class within <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement" target="_blank" rel="noopener">using</a> statement:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91714058" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_with_using-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_with_using.cs content, created by dsibinski on 07:12PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_with_using.cs">
<tr>
<td id="file-dispose_with_using-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_with_using-cs-LC1" class="blob-code blob-code-inner js-file-line">  using (UnmanagedClass myClass = new UnmanagedClass())</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_with_using-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_with_using-cs-LC3" class="blob-code blob-code-inner js-file-line">      // working with the instance&#8230;</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-dispose_with_using-cs-LC4" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/aba29f9bdf87bc129be4948e1e4c9995/raw/53e114999bbaeec03f5fdfc9eb5b29848f0fb882/Dispose_with_using.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/aba29f9bdf87bc129be4948e1e4c9995#file-dispose_with_using-cs" class="Link--inTextBlock"><br />
          Dispose_with_using.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>How does <span style="color: #ff6600;">using</span> statement ensure that <span style="color: #ff6600;">Dispose()</span> is called on our object created within it?</p>
<p>Let&#8217;s see the IL:</p>
<p><figure id="attachment_2792" aria-describedby="caption-attachment-2792" style="width: 745px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2792" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/using_il/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?fit=745%2C763&amp;ssl=1" data-orig-size="745,763" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="using_IL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?fit=745%2C763&amp;ssl=1" class="wp-image-2792 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=745%2C763&#038;ssl=1" alt="" width="745" height="763" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?w=745&amp;ssl=1 745w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=293%2C300&amp;ssl=1 293w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=720%2C737&amp;ssl=1 720w" sizes="auto, (max-width: 745px) 100vw, 745px" /></a><figcaption id="caption-attachment-2792" class="wp-caption-text"><span style="font-size: 8pt;">IL of <span style="color: #ff6600;">using</span> statement</span></figcaption></figure></p>
<p>As you can see, the compiler translates <span style="color: #ff6600;">using</span> statement into try-finally block. In the <span style="color: #ff6600;">finally</span> part <span style="color: #ff6600;">Dispose()</span> method is called on our object&#8217;s instance.</p>
<p>This way the compiler ensures that even if there&#8217;s any exception thrown in the <span style="color: #ff6600;">using</span> block, the object will be disposed. That&#8217;s why we should always work with objects that may use unmanaged resources in such a way.</p>
<h1>Summary</h1>
<p>In this 7th post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals</a> series we examined how unmanaged resources are handled within .NET Framework and what&#8217;s the GC&#8217;s role in that process. We got to know two new GC-internal data structures: finalization and fReachable queues. In the end, we got familiar with dispose pattern and <span style="color: #ff6600;">using</span> statement.</p>
<p>I hope it helped you to clarify these topics a bit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>See you next week! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-3" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1779348816" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-3" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/">[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2779</post-id>	</item>
		<item>
		<title>[.NET Internals 06] Generational garbage collection</title>
		<link>https://www.codejourney.net/net-internals-06-generational-garbage-collection/</link>
					<comments>https://www.codejourney.net/net-internals-06-generational-garbage-collection/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 29 Aug 2018 13:00:52 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2741</guid>

					<description><![CDATA[<p>Continuing .NET Internals series on the blog, today we&#8217;re going to see what is generational garbage collection. You&#8217;ll also get to know what is a card table data structure and for what it&#8217;s used 🙂 Heaps generations As we know from this post, heaps used by .NET process to allocate reference objects are allocated on&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-06-generational-garbage-collection/">[.NET Internals 06] Generational garbage collection</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Continuing .<a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">NET Internals series on the blog</a>, today we&#8217;re going to see what is <em>generational garbage collection</em>. You&#8217;ll also get to know what is a <em>card table</em> data structure and for what it&#8217;s used <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2741"></span></p>
<h1>Heaps generations</h1>
<p>As we know from <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">this post</a>, heaps used by .NET process to allocate reference objects are allocated on different kinds of heaps. In <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">the previous article</a> we also got to know that only Small Object Heap (SOH) is the subject of compaction process. Large Object Heap (LOH) is not compacted because of the performance reasons.</p>
<p>This is however not the only optimization introduced by GC contributors into Small Object Heap. SOH in .NET is also divided into <strong>3 generations</strong>:</p>
<ul>
<li>Generation 0 &#8211; containing newly created objects, which did not have any collection performed on them so far,</li>
<li>Generation 1 &#8211; storing objects that survived a single garbage collection (were not reclaimed during it because of still being in use),</li>
<li>Generation 2 &#8211; keeping long-lived objects that survived two or more GC cycles.</li>
</ul>
<p><span style="font-size: 10pt;">LOH is not divided into generations. More details on LOH management in the article linked just before the &#8220;Summary&#8221; section below.</p>
<p></span></p>
<p>Thanks to such a division of managed heap, the actual collection is performed not on the whole heap, but only on one of the generations, where:</p>
<blockquote>
<p><em>to perform a collection on generation X</em> == to collect objects on generation X and all its younger generations</p>
</blockquote>
<p>That&#8217;s why a <strong>generation 2 collection is knows as a full garbage collection</strong>. During this process objects present on all heaps (on all generations: gen 0, gen 1 and gen 2) are examined and reclaimed. Obviously, this collection is also the most costly one.</p>
<h1>Collection survivors</h1>
<p>In that place we should introduce a term <em>collection survivor</em>. It can be defined as an object which <em>survives</em> the collection (is not collected during GC collection cycle as it&#8217;s still referenced by something).</p>
<p>Knowing that, the following &#8220;promotion rules&#8221; can be defined:</p>
<ul>
<li>object <strong>survives</strong> <strong>generation 0</strong> collection =&gt; object is <strong>promoted to generation 1</strong>,</li>
<li>object <strong>survives generation 1</strong> collection =&gt; object is <strong>promoted to generation 2</strong>,</li>
<li>object <strong>survives generation 2</strong> collection =&gt; object <strong>stays in generation 2</strong>.</li>
</ul>
<h1>Collection thresholds in generations</h1>
<p>In the <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">5th post in the series</a>, it was mentioned that one of the conditions on which the garbage collection can be triggered is when &#8220;the memory used by the objects on the managed heap exceeds some defined threshold&#8221;. In fact, this is not a single threshold, but several thresholds. More precisely, there&#8217;s a separate one per generation. As soon as size of all objects in a particular generation exceeds threshold&#8217;s value, the collection is started.</p>
<p>In the beginning, the thresholds&#8217; values for each generation are initialized to the following values:</p>
<ul>
<li>gen 0: ~256K,</li>
<li>gen 1: ~2MBs,</li>
<li>gen 2: ~10MBs.</li>
</ul>
<p>Nonetheless, these are only <strong>initial</strong> values and are adjusted by the GC at runtime. One of the conditions to increase a particular threshold&#8217;s value is then the survival rate in a generation is high (more objects from particular generation are either promoted to the next one or stay in generation 2), which makes the GC cycles to run less frequently (the condition of exceeding the threshold is not met that often).</p>
<p>This approach seems reasonable, as the main goal of GC is to collect as many objects as possible and reclaim their memory, not to &#8220;waste time&#8221; only to get to know that most of the objects are still in use.</p>
<p>In general, CLR tries to find a balance between two factors:</p>
<ul>
<li>not letting application&#8217;s working memory set to get too big,</li>
<li>not allowing GC to take too much time.</li>
</ul>
<h1>Structure of generational heap</h1>
<p>The diagram below presents how SOH actually looks like being divided into above-described 3 generations:</p>
<p><figure id="attachment_2747" aria-describedby="caption-attachment-2747" style="width: 640px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2747" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/soh_generations/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?fit=640%2C399&amp;ssl=1" data-orig-size="640,399" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="SOH_Generations" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?fit=640%2C399&amp;ssl=1" class="wp-image-2747 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?resize=640%2C399&#038;ssl=1" alt="" width="640" height="399" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?w=640&amp;ssl=1 640w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?resize=300%2C187&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></a><figcaption id="caption-attachment-2747" class="wp-caption-text"><span style="font-size: 8pt;">SOH &#8211; generations, <a href="https://www.red-gate.com/library/under-the-hood-of-net-memory-management" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>As can be noticed, the next object pointer (you can read more about it <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener">in this post</a>) refers to the place after the last object in generation 0. That&#8217;s how it happens that newly created objects are always allocated in generation 0.</p>
<h1>Generational GC cycle</h1>
<p>The following schema very clearly presents how the full generational collection looks like (click to enlarge to see it clearly):</p>
<p><figure id="attachment_2748" aria-describedby="caption-attachment-2748" style="width: 1429px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2748" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/generations_collection/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?fit=1429%2C553&amp;ssl=1" data-orig-size="1429,553" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Generations_Collection" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?fit=1024%2C396&amp;ssl=1" class="wp-image-2748 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=1140%2C441&#038;ssl=1" alt="" width="1140" height="441" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?w=1429&amp;ssl=1 1429w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=300%2C116&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=768%2C297&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=1024%2C396&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=720%2C279&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></a><figcaption id="caption-attachment-2748" class="wp-caption-text"><span style="font-size: 8pt;">Full GC, <a href="https://www.telerik.com/blogs/understanding-net-garbage-collection" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>The first step is generation 0 collection. You can notice that objects <em>H</em> and <em>D</em> are not referenced by anything, so after the first cycle on gen 0 is performed, these objects are reclaimed and not promoted to gen 1. The same happens with object <em>F</em>, which is not being referenced to anymore when the collection on generation 1 is performed &#8211; that&#8217;s why it&#8217;s reclaimed during this step and not promoted to generation 2. In the end of the full GC cycle, only still-referenced objects stay on generation 2.</p>
<p>What&#8217;s also important to notice is that <strong>after each collection generation 0 becomes empty</strong> (contains no objects). Generation 1 may still contain objects promoted from generation 0 and generation 2 may contain long-lived objects.</p>
<h1>Why is static data harmful for GC?</h1>
<p>Having the knowledge presented in this post, we can deduce that the more objects are stored on a generation the longer collection process lasts. What we should also already be able to see is that generation 2 contains long-lived objects which are mostly static or global objects that survive garbage collection cycles (as there&#8217;s always a &#8220;live&#8221; reference to them in the application).</p>
<p>Of course, there are some reasons why static data can be justified (e.g. server-side apps storing some context<span style="font-size: 1rem;">), but <strong>normally using static data should be avoided as much as possible and reasonable</strong>. I think you already know why &#8211; it simply incurs the application&#8217;s performance by making garbage collector&#8217;s work harder and longer.</span></p>
<h1>Cross-generation references</h1>
<p>There&#8217;s also one very interesting issue in having the managed heap divided into generations. Can you imagine the case, when an object is already promoted to gen 2, but one of its reference-typed properties has just been initialized in gen 0? Consider the following code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91541541" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-generations_crossref-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Generations_crossRef.cs content, created by dsibinski on 05:30PM on August 25, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Generations_crossRef.cs">
<tr>
<td id="file-generations_crossref-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-generations_crossref-cs-LC1" class="blob-code blob-code-inner js-file-line">  public class GuyFromGen2</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-generations_crossref-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-generations_crossref-cs-LC3" class="blob-code blob-code-inner js-file-line">      private YoungObject _youngObject;</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-generations_crossref-cs-LC4" class="blob-code blob-code-inner js-file-line">      public void CreateYoungObject()</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-generations_crossref-cs-LC5" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-generations_crossref-cs-LC6" class="blob-code blob-code-inner js-file-line">          _youngObject = new YoungObject();</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-generations_crossref-cs-LC7" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-generations_crossref-cs-LC8" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c03d860c4066d40d029cf74b4dc5b90b/raw/9f4dadbef535b000ca164df736704e9df8ed1a71/Generations_crossRef.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c03d860c4066d40d029cf74b4dc5b90b#file-generations_crossref-cs" class="Link--inTextBlock"><br />
          Generations_crossRef.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Let&#8217;s assume that an instance of <span style="color: #ff6600;">GuyFromGen2</span> has already been created long time ago and it&#8217;s already promoted to generation 2. At this moment someone calls <span style="color: #ff6600;">CreateYoungObject()</span> method, which initializes <span style="color: #ff6600;">_youngObject</span> variable. This makes the &#8220;parent&#8221; instance of <span style="color: #ff6600;">GuyFromGen2 <span style="color: #333333;">holding a reference to its instance object located in gen 0. </p>
<p></span></span></p>
<p>When there&#8217;s a generation 0 collection triggered (which, as we said, examines only objects in generation 0) at this exact moment, it would find <span style="color: #ff6600;">_youngObject</span> allocated on the heap having no gen 0 references to it (as it doesn&#8217;t check gen 2 references during gen 0 collection) so it would assume the object not being used and reclaim its memory.</p>
<p>Fortunately, .NET has a solution for this issue &#8211; <strong>card table</strong> data structure.</p>
<h2>Card table data structure</h2>
<p>Card table is used by .NET&#8217;s memory management system to store information about objects from older generation (gen 2 in that case) that reference younger objects (from gen 0 or gen 1). The execution engine adds an entry into card table as soon as any reference to gen 0 or gen 1 object is created &#8220;inside&#8221; gen 2 object.</p>
<p>For performance optimization reasons the card table stores this information per &#8220;bit&#8221;, which represents 128 bytes (or 256 bytes in 64-bit architectures) of managed memory. That&#8217;s how the card table can be imagined:</p>
<p><figure id="attachment_2751" aria-describedby="caption-attachment-2751" style="width: 696px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2751" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/card_table/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?fit=696%2C453&amp;ssl=1" data-orig-size="696,453" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Card_Table" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?fit=696%2C453&amp;ssl=1" class="wp-image-2751 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?resize=696%2C453&#038;ssl=1" alt="" width="696" height="453" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?w=696&amp;ssl=1 696w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?resize=300%2C195&amp;ssl=1 300w" sizes="auto, (max-width: 696px) 100vw, 696px" /></a><figcaption id="caption-attachment-2751" class="wp-caption-text"><span style="font-size: 8pt;">Card table, <a href="https://www.red-gate.com/library/under-the-hood-of-net-memory-management" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>Then, as soon as gen 0 or gen 1 collection takes place, apart from examining references only from the particular generation&#8217;s roots, GC also checks which memory ranges have their bits set to 1, finds out which objects are allocated within these memory ranges and treats them as potential GC roots (analyzing what these objects reference).</p>
<p>What&#8217;s more, as <a href="https://twitter.com/konradkokosa" target="_blank" rel="noopener">Konrad</a> pointed out in his comment, because of write barrier optimization the whole bytes (8-bit chunks, not only single bits as presented on the figure above) are marked as potential roots sources. So in fact, such cross-generations reference can mark up to 2048 bytes (for 64-bit architectures: <em>256 bytes x 8 = 2048 bytes</em>) memory chunk as a potential GC roots source.</p>
<p>Every referenced object found this way is added to the list of objects still in use (if you still don&#8217;t know what are GC roots and still in use objects list, <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">read the previous post now</a>).</p>
<h1>but&#8230; what about LOH?</h1>
<p>If you&#8217;re curious about Large Object Heap (LOH) in-depth memory organization, I recommend you reading <a href="https://blogs.msdn.microsoft.com/maoni/2016/05/31/large-object-heap-uncovered-from-an-old-msdn-article/" target="_blank" rel="noopener">this article by Maoni Stephens</a>. I can just mention that LOH has its own memory threshold which can be exceeded and it also triggers Gen 2 collection &#8211; from GC point-of-view, collection of objects allocated on LOH happens only during Gen 2 collection.</p>
<p>&nbsp;</p>
<h1>Summary</h1>
<p>We went through the concept of having SOH managed heap divided into 3 generations. By understanding how objects are promoted between generations and the implications of being a long-lived object we saw the potential harmful impact of static data on our application&#8217;s performance.</p>
<p>Another interesting thing we pointed out was the card table data structure used to solve cross-generations references issue.</p>
<p>Next week we&#8217;ll see more on unmanaged resources and objects&#8217; finalization.</p>
<p>Stay tuned! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/net-internals-06-generational-garbage-collection/">[.NET Internals 06] Generational garbage collection</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-06-generational-garbage-collection/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2741</post-id>	</item>
		<item>
		<title>[.NET Internals 05] Garbage collection: marking, collection and heaps compaction</title>
		<link>https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/</link>
					<comments>https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 22 Aug 2018 13:00:35 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2712</guid>

					<description><![CDATA[<p>Today, in the next article from .NET Internals series on my blog, we&#8217;re going to investigate how the garbage collector (GC) actually releases the memory (which is its main purpose as could be read here), what is marking phase and how the managed heaps are compacted in order to optimize the process. We&#8217;ll also see&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/">[.NET Internals 05] Garbage collection: marking, collection and heaps compaction</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today, in the next article from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a> on my blog, we&#8217;re going to investigate how the garbage collector (GC) actually releases the memory (which is its main purpose as <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener">could be read here</a>), what is <em>marking phase</em> and how the <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">managed heaps</a> are <em>compacted</em> in order to optimize the process. We&#8217;ll also see when may the collection be triggered.<br />
<span id="more-2712"></span></p>
<h1>Finding objects to be garbage-collected</h1>
<p>As we <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener">already know</a>, .NET doesn&#8217;t allow developers to directly allocate the objects on the heap. Instead, the only thing the programmer needs to do is to use the <span style="color: #ff6600;">new</span> keyword &#8211; framework takes care of all the rest (placing the object on the proper heap, initializing it etc.). After that, you can simply forget about your object, because it is released (collected) automatically by the garbage collector as soon as it&#8217;s not needed anymore. But how does the GC know which objects it can collect?</p>
<p>In principle, <strong>all the garbage collector does is looking for the allocated objects which aren&#8217;t referenced by anything</strong>, which means that such objects are no longer needed. This makes such objects ready to be collected (their memory can be released &#8211; marked as being possible to be used again).</p>
<p>There are several sources of references to objects allocated on the heap:</p>
<ul>
<li>stack (as we know from <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">the 2nd post</a>),</li>
<li>global or static reference variables,</li>
<li>CPU registers,</li>
<li>interop references (.NET objects used in COM/API calls),</li>
<li>objects finalization references.</li>
</ul>
<h2>GC roots tree</h2>
<p>All above-listed sources are called <em>GC roots</em> (also referred to as <em>root references</em>). As objects referenced from any of the roots can reference another objects (for example a customer may reference its orders collection), all these nested references are represented as a tree (graph) for every .NET application. Such references tree may look as follows:</p>
<p><figure id="attachment_2713" aria-describedby="caption-attachment-2713" style="width: 658px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2713" data-permalink="https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/gc_referncestree/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?fit=658%2C228&amp;ssl=1" data-orig-size="658,228" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="GC_ReferncesTree" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?fit=658%2C228&amp;ssl=1" class="wp-image-2713 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?resize=658%2C228&#038;ssl=1" alt="" width="658" height="228" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?w=658&amp;ssl=1 658w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?resize=300%2C104&amp;ssl=1 300w" sizes="auto, (max-width: 658px) 100vw, 658px" /></a><figcaption id="caption-attachment-2713" class="wp-caption-text"><span style="font-size: 8pt;">Source: <em>Under the Hood of .NET memory Management</em></span></figcaption></figure></p>
<p>As you can see, GC root is present on the stack, pointing to <em>Customer</em> reference object. It contains an <em>ArrayList</em> collection of orders, which is referenced by <em>Customer</em> object. The collection itself also contains references to its elements, so the tree grows up.</p>
<p>Each root contains either a reference (address) to some object or null value.</p>
<h2>Unreachable (not used) objects</h2>
<p>The GC roots tree described above is used by garbage collector to know which objects are no longer needed. As we see, the graph contains all objects that are still in use (are referenced by something else).</p>
<p>GC uses this information the other way around &#8211;  generally the <strong>GC classifies all objects that are not reachable from any root (not present in the graph) as garbage</strong>. Such objects are then collected (the memory allocated for them is released) by the GC during its <em>collection cycles</em>, which will be described in details in the next posts in the series.</p>
<h1>Memory releasing (garbage collection)</h1>
<p>As mentioned, garbage collection is a process executed in cycles, which will be covered in the later articles, but the process itself contains two main steps:</p>
<ol>
<li><strong>Marking phase</strong> &#8211; finding which objects are still in use,</li>
<li><strong>Collection</strong> &#8211; actual collection process of not-anymore-used objects (including SOH compaction).</li>
</ol>
<p>Let&#8217;s see both phases in details.</p>
<h2>Marking phase</h2>
<p>When garbage collector runs its memory releasing process (referred to as &#8216;collection&#8217;), it needs to know which objects on the heap are still in use by the application &#8211; obviously, such objects cannot be collected.</p>
<p>In order to obtain this information, GC<strong> goes through the whole root references tree</strong> and for each GC root moves along all its reference tree (all objects that are referenced from the particular root) <strong>in order to <em>mark</em> each object in this tree as &#8220;still in use&#8221;</strong>. That&#8217;s why this integrated part of garbage collection process is called <em>marking phase</em>.</p>
<p>Marking is a recursive operation, because as we said before, roots reference some object, which references another object, which references another object&#8230;</p>
<p>so in order to make sure that every object in use is added to the &#8220;still in use&#8221; list (if it&#8217;s not there yet), this recursive marking is done as can be seen below:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91434616" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-gc_marking_pseudocode-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="GC_Marking_PseudoCode.cs content, created by dsibinski on 06:30PM on August 20, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="GC_Marking_PseudoCode.cs">
<tr>
<td id="file-gc_marking_pseudocode-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-gc_marking_pseudocode-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Mark(objectRef o)</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-gc_marking_pseudocode-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-gc_marking_pseudocode-cs-LC3" class="blob-code blob-code-inner js-file-line">      if (!InUseList.Exists(o))</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-gc_marking_pseudocode-cs-LC4" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-gc_marking_pseudocode-cs-LC5" class="blob-code blob-code-inner js-file-line">          InUseList.Add(o);</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-gc_marking_pseudocode-cs-LC6" class="blob-code blob-code-inner js-file-line">          List refs = GetAllChildReferences(o);</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-gc_marking_pseudocode-cs-LC7" class="blob-code blob-code-inner js-file-line">          foreach (objectRef childRef in refs)</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-gc_marking_pseudocode-cs-LC8" class="blob-code blob-code-inner js-file-line">          {</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-gc_marking_pseudocode-cs-LC9" class="blob-code blob-code-inner js-file-line">              Mark(childRef);</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-gc_marking_pseudocode-cs-LC10" class="blob-code blob-code-inner js-file-line">          }</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-gc_marking_pseudocode-cs-LC11" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-gc_marking_pseudocode-cs-LC12" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-gc_marking_pseudocode-cs-LC13" class="blob-code blob-code-inner js-file-line"> // source: Under the Hood of .NET Memory Management</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/894cc10e61c3d6eca437e5690353b010/raw/f1805b55958269fb920fc90812e9139785760b39/GC_Marking_PseudoCode.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/894cc10e61c3d6eca437e5690353b010#file-gc_marking_pseudocode-cs" class="Link--inTextBlock"><br />
          GC_Marking_PseudoCode.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Let&#8217;s now see how it fits into the actual collection operation.</p>
<h2>Collection</h2>
<p>The actual collection process, including previously-examined marking phase, can be pictured with the following pseudo-code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91434554" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-gc_collect_pseudocode-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="GC_Collect_PseudoCode.cs content, created by dsibinski on 06:26PM on August 20, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="GC_Collect_PseudoCode.cs">
<tr>
<td id="file-gc_collect_pseudocode-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-gc_collect_pseudocode-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Collect()</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-gc_collect_pseudocode-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-gc_collect_pseudocode-cs-LC3" class="blob-code blob-code-inner js-file-line">      List gcRoots = GetAllGCRoots();</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-gc_collect_pseudocode-cs-LC4" class="blob-code blob-code-inner js-file-line">      foreach (objectRef root in gcRoots)</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-gc_collect_pseudocode-cs-LC5" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-gc_collect_pseudocode-cs-LC6" class="blob-code blob-code-inner js-file-line">          Mark(root);</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-gc_collect_pseudocode-cs-LC7" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-gc_collect_pseudocode-cs-LC8" class="blob-code blob-code-inner js-file-line">      Cleanup();</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-gc_collect_pseudocode-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-gc_collect_pseudocode-cs-LC10" class="blob-code blob-code-inner js-file-line">// source: Under the Hood of .NET Memory Management</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7902dcca5400b36b0751ca69ed8124e5/raw/e4d581bdd45849ed14be3db1c75a37e73c4b7850/GC_Collect_PseudoCode.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7902dcca5400b36b0751ca69ed8124e5#file-gc_collect_pseudocode-cs" class="Link--inTextBlock"><br />
          GC_Collect_PseudoCode.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>First of all, GC gets a list of all GC roots in the application (the list is maintained by JIT compiler and the runtime). Then it needs to iterate through each root and perform marking operation on it. Knowing that marking is a recursive operation, after this phase is finished, GC can be sure that all objects that have any root reference (either direct one or being pointed to by another objects) are added to the list of objects in use.</p>
<p>Next step is the actual memory releasing process of not used objects, represented as a call to <span style="color: #ff6600;">Cleanup()</span> method on the listing above. Memory cleanup itself is a very simple process &#8211; it&#8217;s just marking a particular memory block(s) as free (not used). There&#8217;s no overwriting of memory or anything like that <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> (except &#8216;side overwriting&#8217; which happens during heaps compaction &#8211; described below). Just simple boolean-like terminology is used for memory blocks &#8211; used (1) or not used (0). It works that simple for LOH , but collection on SOH (still don&#8217;t know what are <em>LOH</em> and <em>SOH</em>? Go and <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">read here</a> quickly!) also involves the <em>compaction</em> process. Let&#8217;s see what that is.</p>
<h2>Heaps compaction</h2>
<p>As we know from <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">the first post</a>, memory on the managed heaps can get fragmented, leaving holes of not used memory between live objects. That&#8217;s why the garbage collection for SOH process involves <strong><em>compaction</em>, which is a process of removing the memory holes on the heap</strong>. It&#8217;s often referred to as a<em> Copy Collection</em> process, because it&#8217;s based on finding the dead objects or memory holes (it&#8217;s actually the same &#8211; holes of the memory that are not used by anything, present in-between live objects) and overwriting these holes with the live objects allocated later (next) on the heap &#8211; by copying chunks of live objects &#8216;down in the heap&#8217;.</p>
<p>The <strong>result of the compaction process</strong> is the contiguous SOH, where <strong>objects are allocated on top of each other with no or minimal possible number of memory holes</strong>.</p>
<p>Finally, addresses to the objects stored in reference variables are updated in order to point to the correct, new places in the memory occupied by particular object.</p>
<p>The best gain we get from the compaction is that the SOH is not fragmented, so the memory can be used efficiently. On the other hand it requires some CPU time, which may have some impact on our application&#8217;s performance.</p>
<p>By default, LOH is not compacted because of the size of objects stored on it (&gt;85 kilobytes). Copying chunks of such objects would take too much time. Instead, used space and memory holes on the LOH are tracked and the allocation algorithm is adjusted to try to reserve the memory for new objects in the optimal way (by finding the best possible free slots on the fragmented heap).</p>
<p>What&#8217;s worth noticing is that starting from .NET Framework 4.5.1, LOH compaction can be enabled on demand by using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.gcsettings.largeobjectheapcompactionmode?view=netframework-4.7.2" target="_blank" rel="noopener">GCSettings.LargeObjectHeapCompactionMode property</a>.</p>
<h1>When does the GC run?</h1>
<p>It can be stated that GC works in a non-deterministic manner. It runs on a separate thread when one of the following conditions becomes true:</p>
<ul>
<li> the OS sends low memory notification,</li>
<li>the memory used by the objects on the managed heap exceeds some defined threshold (which is adjusted dynamically at runtime, based on current allocations),</li>
<li><span style="color: #ff6600;">GC.Collect()</span> method is called in the code.</li>
</ul>
<p>If you see <span style="color: #ff6600;">GC.Collect()</span> directly used in code, in almost every case it means that there&#8217;s something wrong with the application&#8217;s implementation. Several great Microsoft engineers and open-source contributors have worked on automatic garbage collection in order to not trigger it manually <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The exceptions for this rule I&#8217;d accept are maybe some gaming implementations, in which you work with huge objects and sometimes you&#8217;d like to affect the way when these objects&#8217; memory is cleaned-up or usage in debugging &#8211; most of memory profilers (like <a href="https://www.jetbrains.com/dotmemory/" target="_blank" rel="noopener">dotMemory</a> or <a href="https://www.red-gate.com/products/dotnet-development/ants-memory-profiler/index" target="_blank" rel="noopener">ANTS Memory Profiler</a>) force the collection before the memory snapshot is done by the user. This is reasonable, because when debugging memory leaks or issues you wanna see which objects remain allocated after GC does its cleanup.</p>
<p>What&#8217;s also worth mentioning is that when the garbage collection is run, all threads are stopped by default, except the thread in which the collection was triggered. However, this can be configured by changing the GC&#8217;s settings to work in workstation or server mode, as well as making it run concurrently or in the background. There are different use cases in which each settings combination should be used &#8211; you can find more details about it <a href="https://blogs.msdn.microsoft.com/seteplia/2017/01/05/understanding-different-gc-modes-with-concurrency-visualizer/" target="_blank" rel="noopener">here</a> and <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals" target="_blank" rel="noopener">here</a>.</p>
<h1>Summary</h1>
<p>Today we&#8217;ve covered the main blocks from which the garbage collection process in .NET is built. We went through marking phase, then the actual collection process &#8211; also including heaps compaction. We learnt how the GC roots tree is built and how garbage collector knows which objects it can clean-up during its cycle. We also listed cases in which the collection can be triggered.</p>
<p>In the next post we&#8217;ll examine a very interesting concept &#8211; generational garbage collection.</p>
<p>See ya next week! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/">[.NET Internals 05] Garbage collection: marking, collection and heaps compaction</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2712</post-id>	</item>
		<item>
		<title>[.NET Internals 04] What is Garbage Collection? Memory allocation in .NET</title>
		<link>https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/</link>
					<comments>https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 15 Aug 2018 06:00:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2670</guid>

					<description><![CDATA[<p>In the next, 4th post from .NET Internals series, we&#8217;re going to meet a new friend called Garbage Collector, discuss this guy&#8217;s main responsibilities and see what is memory allocation in .NET applications and how it works. Ready? Let&#8217;s start then! 😉 What (or who) is Garbage Collection (Collector)? As you could read in the previous&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/">[.NET Internals 04] What is Garbage Collection? Memory allocation in .NET</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the next, 4th post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a>, we&#8217;re going to meet a new friend called <em>Garbage Collector</em>, discuss this guy&#8217;s main responsibilities and see what is memory allocation in .NET applications and how it works.</p>
<p>Ready? Let&#8217;s start then! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2670"></span></p>
<h1>What (or who) is Garbage Collection (Collector)?</h1>
<p>As you could read in the <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">previous posts</a> on internal details of .NET,  there are a lot of conditions and assumption of memory organization in the framework. Data is stored <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">on the proper structures</a>, sometimes <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing/" target="_blank" rel="noopener">boxed and unboxed</a>, but what&#8217;s the best about it all is that <strong>it&#8217;s almost completely invisible for us &#8211; developers</strong>.</p>
<p>In fact, providing this <em>invisibility </em>is a goal of <em>Garbage Collector</em> <em>(GC)</em>. It should become our close friend (it&#8217;s not that scary as you could have heard &#8211; we&#8217;ll see that soon <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ), because this <strong>automatic memory manager</strong> does a lot of stuff for us, including:</p>
<ul>
<li>allowing us to write code without having to release memory (still remember <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">the meme about C++?</a>),</li>
<li>performing heap allocations in an efficient way,</li>
<li>reclaiming the objects that are no longer used and clearing their memory,</li>
<li>ensuring that every new managed object gets clean content to begin with, so there is no work to be done in an object&#8217;s constructor to allocate the memory for all its members,</li>
<li>providing memory safety, so one object cannot use the memory reserved for another object.
</li>
</ul>
<p>The term &#8216;garbage collection&#8217; was firstly used in <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)" target="_blank" rel="noopener">LISP programming language</a> in 1959 and since then it represents the concept of automatic memory management in programming languages and frameworks.</p>
<h1>Does GC allocate or deallocate the memory?</h1>
<p>There&#8217;s often this confusion between allocating and deallocating the memory &#8211; what is actually responsible for that? In principle, <strong>the goal of garbage collector is to</strong> <strong>deallocate the memory</strong> &#8211; as its name suggests, it <em>collects</em> (frees, reclaims) the <em>garbage</em> (not-anymore-needed objects).</p>
<p>On the other hand, when there&#8217;s any memory allocation request sent by an application, such query is transferred to CLR, which is actually responsible for allocating the memory. However, as we&#8217;ll see in the coming posts, the deallocation of memory (which is much more complex process that allocating it) can be triggered on various conditions and it can happen that <strong>allocation of the memory requires deallocation to be performed first</strong>. It doesn&#8217;t mean that this is a sequence of events (i.e. before allocation the deallocation is performed), but that the number of allocations done by the CLR can affect the way and frequency of garbage collections (we&#8217;d like to have available memory when an allocation is to be done).</p>
<p>That&#8217;s how the CLR &#8216;asks&#8217; GC for help (or &#8216;communicates with GC&#8217; by notifying it about allocations) in actually allocating the memory (for instance by making GC running a collection or heap compaction process more frequently). Because of that reason, it&#8217;s usually simplified that garbage collector handles both allocation and deallocation of memory.</p>
<p>As we&#8217;ll see below, <strong>allocation of memory is as simple as <em>1 + 2 = 3</em></strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; continue reading to get to know why!</p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-4" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1779348819" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-4" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<h1>Memory allocation in .NET</h1>
<p>As we read in the <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">first post of the series</a>, each process has its own virtual address space. Garbage collector is responsible for allocating the memory on the managed heaps (more about heaps <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">here</a>) created in this process&#8217;s space. It means that <strong>garbage collector only takes care of reference type objects</strong>.</p>
<p>Value types are stored on the stack in LIFO order and their memory is reclaimed as soon as the method in which these value types are defined exits. It would make no sense if GC had to manage these theoretically simple and (in a perfect world) locally declared variables.</p>
<h2>Next object pointer</h2>
<p>To make it simple, as soon as managed heap is created, it contains a <em>pointer</em> to the memory address where the next object will be allocated. This pointer is simply a number and is referred to as <em>next object pointer</em>. Initially, its value is set to managed heap&#8217;s base address:</p>
<p>&nbsp;</p>
<p><figure id="attachment_2684" aria-describedby="caption-attachment-2684" style="width: 391px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2684" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/nop/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?fit=391%2C320&amp;ssl=1" data-orig-size="391,320" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NOP" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?fit=391%2C320&amp;ssl=1" class="wp-image-2684 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?resize=391%2C320&#038;ssl=1" alt="" width="391" height="320" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?w=391&amp;ssl=1 391w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?resize=300%2C246&amp;ssl=1 300w" sizes="auto, (max-width: 391px) 100vw, 391px" /></a><figcaption id="caption-attachment-2684" class="wp-caption-text"><span style="font-size: 8pt;">Managed heap and next object pointer</span></figcaption></figure></p>
<p>As soon as the first-ever reference object is to be allocated on this particular heap, the memory is allocated in the place where the next object pointer currently points to. State of the heap after first allocation would be something like that:</p>
<p><figure id="attachment_2685" aria-describedby="caption-attachment-2685" style="width: 395px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2685" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/nop_after1stallocation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?fit=395%2C318&amp;ssl=1" data-orig-size="395,318" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NOP_After1stAllocation" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?fit=395%2C318&amp;ssl=1" class="wp-image-2685 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?resize=395%2C318&#038;ssl=1" alt="" width="395" height="318" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?w=395&amp;ssl=1 395w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?resize=300%2C242&amp;ssl=1 300w" sizes="auto, (max-width: 395px) 100vw, 395px" /></a><figcaption id="caption-attachment-2685" class="wp-caption-text"><span style="font-size: 8pt;">Managed heap and next object pointer after allocation</span></figcaption></figure></p>
<p>As presented above, the next object pointer is moved to the address just after the allocated object. It ensures that there are no unnecessary memory gaps on the heap.</p>
<h2>Complexity of memory allocation</h2>
<p>In reality, the next object pointer&#8217;s value is a number in hexadecimal format (e.g. <em>0xF7279</em>). When a new allocation is to be made, <strong>the only operation to perform is an addition operation</strong>. It is known how much space is needed for the new object (more details in the next section), so in order to reserve the proper memory chunk, number of bytes necessary for a new object is added to the next object pointer&#8217;s current value.</p>
<p>This is how the reservation of managed memory works. Because of that it can be said that allocating the memory for reference types is almost as fast as allocating variables on the stack.</p>
<p>If you&#8217;d like to see how you can check the memory address of an object, I recommend <a href="https://gooroo.io/GoorooTHINK/Article/17038/Pointers-and-Unsafe-Code-in-C-everything-you-need-to-know/25066" target="_blank" rel="noopener">checking this article</a>.</p>
<h1>How is an object&#8217;s size calculated?</h1>
<p>In the comments under <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing" target="_blank" rel="noopener">the previous post</a>, Jelena asked for explanation on how the size of an object is calculated. Here it comes <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>As we all know <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">from the second post</a>, object is sometimes allocated on the Small Object Heap (SOH) or Large Object Heap (LOH) depending on its size. For that reason before the allocation is made, the object&#8217;s size must be determined. How is this size calculated then?</p>
<p>It would make things easy to assume that size of an object is everything it contains (also other objects&#8217; sizes). In reality, it&#8217;s not counted this way. Objects contained in another objects are allocated separately on the heap, so their actual sizes are not included in the parent object&#8217;s size.</p>
<p>Very good example is given in Chris Farrell&#8217;s and Nick Harrison&#8217;s book &#8211; <em>Under the Hood of .NET Memory Management</em>. If we consider the following code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91326246" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-string_array_allocation-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="string_array_allocation.cs content, created by dsibinski on 05:07PM on August 14, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="string_array_allocation.cs">
<tr>
<td id="file-string_array_allocation-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-string_array_allocation-cs-LC1" class="blob-code blob-code-inner js-file-line">  class MyClass</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-string_array_allocation-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-string_array_allocation-cs-LC3" class="blob-code blob-code-inner js-file-line">      string Test=&quot;Hello world Wazzup!&quot;; // 19 characters</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-string_array_allocation-cs-LC4" class="blob-code blob-code-inner js-file-line">      byte[] data=new byte[86000]; // 86000 bytes (&gt;85K &#8211; goes on LOH)</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-string_array_allocation-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/e209c3fb74bd5f940d2c44bc140582a5/raw/8a719975e8f847a8ffc863d8c4dcfdfedf6b0368/string_array_allocation.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e209c3fb74bd5f940d2c44bc140582a5#file-string_array_allocation-cs" class="Link--inTextBlock"><br />
          string_array_allocation.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>That&#8217;s how the heaps&#8217; state looks like as soon as as instance of <span style="color: #ff6600;">MyClass</span> is created:</p>
<p><figure id="attachment_2686" aria-describedby="caption-attachment-2686" style="width: 525px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2686" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/stringarray_allocationstate/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?fit=525%2C310&amp;ssl=1" data-orig-size="525,310" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="StringArray_AllocationState" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?fit=525%2C310&amp;ssl=1" class="wp-image-2686 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?resize=525%2C310&#038;ssl=1" alt="" width="525" height="310" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?w=525&amp;ssl=1 525w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?resize=300%2C177&amp;ssl=1 300w" sizes="auto, (max-width: 525px) 100vw, 525px" /></a><figcaption id="caption-attachment-2686" class="wp-caption-text"><span style="font-size: 8pt;">Source: <em>Under the Hood of .NET Memory Management</em></span></figcaption></figure></p>
<p>The size of <span style="color: #ff6600;">MyClass</span> object instance will include:</p>
<ul>
<li>general class stuff (e.g. some metadata &#8211; you can check it yourself in IL code with ILSpy as we did with <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing/" target="_blank" rel="noopener">boxing and unboxing</a>),</li>
<li>memory required to store the pointers (memory addresses) to the string and bytes array.</li>
</ul>
<p><span style="color: #ff6600;">string Test</span> will be allocated on the SOH, and <span style="color: #ff6600;">byte[] data</span> will be allocated on the LOH (it&#8217;s more than 85K).</p>
<p>In general, the size of an object is calculated by adding sizes of:</p>
<ul>
<li>general class data,</li>
<li>pointers (for reference types class members) containing only addresses in memory (hexadecimal numbers),</li>
<li>value types (for value types class members) &#8211; more details <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sizeof" target="_blank" rel="noopener">here</a>.</li>
</ul>
<h1>Summary</h1>
<p>I hope this post makes the role of garbage collector a bit more clear for you. We&#8217;ve also seen how easy the memory allocation is and what&#8217;s the general way of calculating an object&#8217;s size.</p>
<p>Even we don&#8217;t perform the actual allocations ourselves manually and may think like this guy:</p>
<p><figure id="attachment_2691" aria-describedby="caption-attachment-2691" style="width: 500px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2691" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/gc_meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?fit=500%2C344&amp;ssl=1" data-orig-size="500,344" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="GC_Meme" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?fit=500%2C344&amp;ssl=1" class="wp-image-2691 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?resize=500%2C344&#038;ssl=1" alt="" width="500" height="344" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?w=500&amp;ssl=1 500w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?resize=300%2C206&amp;ssl=1 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-2691" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://twitter.com/ben_a_adams/status/895065527197982720" target="_blank" rel="noopener">this Ben Adams&#8217;s tweet</a></span></figcaption></figure></p>
<p>We&#8217;ll see if that&#8217;s true next week, when we&#8217;ll dig into more complex topic, the real purpose of the GC &#8211; releasing the memory!</p>
<p>Stay tuned!</p>
<p>The post <a href="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/">[.NET Internals 04] What is Garbage Collection? Memory allocation in .NET</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2670</post-id>	</item>
		<item>
		<title>[.NET Internals 03] Boxing and unboxing</title>
		<link>https://www.codejourney.net/net-internals-03-boxing-and-unboxing/</link>
					<comments>https://www.codejourney.net/net-internals-03-boxing-and-unboxing/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 08 Aug 2018 06:04:05 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2622</guid>

					<description><![CDATA[<p>As we are already familiar with the basics of memory and data structures used by .NET applications, in this third post from .NET Internals series we&#8217;re going to dig into boxing and unboxing and their performance implications. What is boxing and unboxing? In the previous post we learnt what are value and reference types and got&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/">[.NET Internals 03] Boxing and unboxing</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As we are already familiar with the <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">basics of memory</a> and <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">data structures</a> used by .NET applications, in this third post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a> we&#8217;re going to dig into <em>boxing</em> and <em>unboxing</em> and their performance implications.<br />
<span id="more-2622"></span></p>
<h1>What is boxing and unboxing?</h1>
<p>In the <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">previous post</a> we learnt what are value and reference types and got to know that the former are stored on the stack, whereas the latter are stored on the managed heap. So why should we care? Isn&#8217;t it .NET runtime which correctly manages these data structures and what&#8217;s stored on them so we don&#8217;t need to worry about that?</p>
</p>
<p>In fact, no. What&#8217;s crucial to know and understand are the implications of <strong>moving data from the stack to the heap</strong> and otherwise.</p>
</p>
<p><span style="text-decoration: underline;">Remember</span>:</p>
<ul>
<li>when any <strong>value type</strong> variable is <strong>assigned to a reference type</strong> variable, <strong>data is moved from the stack to the heap</strong> and this is called <strong><span style="text-decoration: underline;">boxing</span>,</strong></li>
<li>when any <strong>reference type</strong> variable is <strong>assigned to a value type</strong> variable, <strong>data is moved from the heap to the stack</strong> and this is called <strong><span style="text-decoration: underline;">unboxing</span>. </strong>
</p>
</li>
</ul>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" target="_blank" rel="noopener">Microsoft Docs examples</a> illustrate these actions very well.</p>
<p>Consider the following example of boxing:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91148841" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxing_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Boxing_example.cs content, created by dsibinski on 07:52PM on August 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Boxing_example.cs">
<tr>
<td id="file-boxing_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxing_example-cs-LC1" class="blob-code blob-code-inner js-file-line">int i = 123;</td>
</tr>
<tr>
<td id="file-boxing_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxing_example-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-boxing_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxing_example-cs-LC3" class="blob-code blob-code-inner js-file-line">// Boxing &#8211; copying the value of i into object o.</td>
</tr>
<tr>
<td id="file-boxing_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-boxing_example-cs-LC4" class="blob-code blob-code-inner js-file-line">object o = i;  </td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/ce84dd9c2feeae51bba1a35e438cf2ac/raw/6b67a8f30617d2ac6377025a01d2fee30834866f/Boxing_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/ce84dd9c2feeae51bba1a35e438cf2ac#file-boxing_example-cs" class="Link--inTextBlock"><br />
          Boxing_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and the memory state as it executes:</p>
<p><figure id="attachment_2625" aria-describedby="caption-attachment-2625" style="width: 228px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2625" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/boxing_example/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?fit=228%2C148&amp;ssl=1" data-orig-size="228,148" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Boxing_Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?fit=228%2C148&amp;ssl=1" class="wp-image-2625 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?resize=228%2C148&#038;ssl=1" alt="" width="228" height="148" /></a><figcaption id="caption-attachment-2625" class="wp-caption-text"><span style="font-size: 8pt;">Boxing, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" target="_blank" rel="noopener">source</a></span></figcaption></figure></p>
<p>In order to store &#8220;123&#8221; value in an <span style="color: #ff6600;">object</span>, the &#8220;box&#8221; is created on the heap and the value is copied inside it.</p>
</p>
<p>On the other hand, when unboxing happens:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91148939" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-unboxing_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Unboxing_Example.cs content, created by dsibinski on 08:00PM on August 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Unboxing_Example.cs">
<tr>
<td id="file-unboxing_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-unboxing_example-cs-LC1" class="blob-code blob-code-inner js-file-line">int i = 123;      // &quot;i&quot; is a value type</td>
</tr>
<tr>
<td id="file-unboxing_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-unboxing_example-cs-LC2" class="blob-code blob-code-inner js-file-line">object o = i;     // boxing &quot;i&quot; into &quot;o&quot;</td>
</tr>
<tr>
<td id="file-unboxing_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-unboxing_example-cs-LC3" class="blob-code blob-code-inner js-file-line">int j = (int)o;   // unboxing &quot;o&quot; into &quot;j&quot;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7ec30a97fb93a7cffbb6e911979f8cbe/raw/36c03294f1506720f87e58379174636088a0e794/Unboxing_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7ec30a97fb93a7cffbb6e911979f8cbe#file-unboxing_example-cs" class="Link--inTextBlock"><br />
          Unboxing_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>that&#8217;s how stack&#8217;s and heap&#8217;s content changes:</p>
<p><figure id="attachment_2631" aria-describedby="caption-attachment-2631" style="width: 228px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2631" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/unboxing_example/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?fit=228%2C215&amp;ssl=1" data-orig-size="228,215" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Unboxing_Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?fit=228%2C215&amp;ssl=1" class="wp-image-2631 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?resize=228%2C215&#038;ssl=1" alt="" width="228" height="215" /></a><figcaption id="caption-attachment-2631" class="wp-caption-text">Unboxing, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<p>Value &#8220;123&#8221; is taken out of the &#8220;box&#8221; and placed back on the stack.</p>
</p>
<p>Notice that when <span style="color: #ff6600;">i</span> value type is boxed into object <span style="color: #ff9900;"><span style="color: #ff6600;">o</span><span style="color: #000000;">,</span> <span style="color: #000000;">there&#8217;s a reference stored on the stack and the actual memory is allocated on the heap (as for all reference types). As soon as the unboxing happens, the real data being on the heap must be copied to the stack (variable <span style="color: #ff6600;">j</span>). In both cases our goal is to deal with the same value (123).</span></span></p>
</p>
<p>As you can imagine, these operations produce some additional cost and affect the performance, which we&#8217;ll discuss in a moment.</p>
<h1>Let&#8217;s see some IL</h1>
<p>When analyzing such performance or memory management aspects in our code (C# in that case), it&#8217;s often worth to see how the <a href="https://en.wikipedia.org/wiki/Common_Intermediate_Language" target="_blank" rel="noopener">Intermediate Language</a> (IL) looks like.</p>
</p>
<p>We haven&#8217;t covered this concept yet, but as you probably know when C# code is compiled into DLL or EXE, these output files actually contain the IL code, which is later JIT-compiled and executed by the virtual machine (more details <a href="https://www.codejourney.net/2018/10/net-internals-10-application-execution-model/" data-wplink-edit="true">here</a>). The .NET runtime must somehow know whether is should box or unbox the particular variable, as it requires some special memory allocation actions to be taken.</p>
</p>
<p>Let&#8217;s create some simple .NET Console Application with the following code in its <span style="color: #ff6600;">Main</span> method:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212016" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxingunboxing_sample-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="BoxingUnboxing_sample.cs content, created by dsibinski on 04:20AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="BoxingUnboxing_sample.cs">
<tr>
<td id="file-boxingunboxing_sample-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxingunboxing_sample-cs-LC1" class="blob-code blob-code-inner js-file-line">  namespace BoxingUnboxingTest</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxingunboxing_sample-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxingunboxing_sample-cs-LC3" class="blob-code blob-code-inner js-file-line">      class Program</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-boxingunboxing_sample-cs-LC4" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-boxingunboxing_sample-cs-LC5" class="blob-code blob-code-inner js-file-line">          static void Main(string[] args)</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-boxingunboxing_sample-cs-LC6" class="blob-code blob-code-inner js-file-line">          {</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-boxingunboxing_sample-cs-LC7" class="blob-code blob-code-inner js-file-line">              int a = 5;</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-boxingunboxing_sample-cs-LC8" class="blob-code blob-code-inner js-file-line">              object o = a;</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-boxingunboxing_sample-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-boxingunboxing_sample-cs-LC10" class="blob-code blob-code-inner js-file-line">              int b = (int)o;</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-boxingunboxing_sample-cs-LC11" class="blob-code blob-code-inner js-file-line">          }</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-boxingunboxing_sample-cs-LC12" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-boxingunboxing_sample-cs-LC13" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/105cc15fdf7cebd08bcfc7751793eca6/raw/5348461bc4a235d7e28b9a71b39c809506fbfab5/BoxingUnboxing_sample.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/105cc15fdf7cebd08bcfc7751793eca6#file-boxingunboxing_sample-cs" class="Link--inTextBlock"><br />
          BoxingUnboxing_sample.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Let&#8217;s compile the application so we can find <em>BoxingUnboxingTest.exe</em> file in the output directory. Now we will use <a href="https://github.com/icsharpcode/ILSpy" target="_blank" rel="noopener">ILSpy</a> to see the IL code inside the executable.</p>
</p>
<p>As soon as the EXE file is opened in ILSpy, we can go directly to see <span style="color: #ff6600;">Main(string[]) : void</span> method&#8217;s compiled content, choosing &#8220;IL with C#&#8221; view to make it simpler for us:</p>
</p>
<p><figure id="attachment_2634" aria-describedby="caption-attachment-2634" style="width: 775px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2634" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/boxingunboxing_il1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?fit=775%2C687&amp;ssl=1" data-orig-size="775,687" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="BoxingUnboxing_IL1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?fit=775%2C687&amp;ssl=1" class="wp-image-2634 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=775%2C687&#038;ssl=1" alt="" width="775" height="687" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?w=775&amp;ssl=1 775w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=300%2C266&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=768%2C681&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=720%2C638&amp;ssl=1 720w" sizes="auto, (max-width: 775px) 100vw, 775px" /></a><figcaption id="caption-attachment-2634" class="wp-caption-text">Boxing and Unboxing in IL</figcaption></figure></p>
<p>Notice the <span style="color: #ff6600;">box</span> statement just after the assignment of value type to reference type happens (<em>object obj = num</em>). Similarly for <span style="color: #ff6600;">unbox.any</span> statement just after assignment of reference type to value type (<em>int num2 = (int)obj</em>).</p>
</p>
<p>That&#8217;s how boxing and unboxing is represented in the IL.</p>
<h1>When do we box and unbox?</h1>
<p>The sample code above may seem naive and you may think &#8220;hey, but I never do such things&#8221;. That&#8217;s true in most cases, but values in our code are often boxed/unboxed even if we are not aware of that.</p>
<h2>Non-generic collections</h2>
<p>For instance, there still exists the old-school <span style="color: #ff6600;">ArrayList</span> collection:</p>
<p><figure id="attachment_2637" aria-describedby="caption-attachment-2637" style="width: 540px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2637" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/arraylist_example/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?fit=540%2C139&amp;ssl=1" data-orig-size="540,139" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ArrayList_Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?fit=540%2C139&amp;ssl=1" class="wp-image-2637 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?resize=540%2C139&#038;ssl=1" alt="" width="540" height="139" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?w=540&amp;ssl=1 540w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?resize=300%2C77&amp;ssl=1 300w" sizes="auto, (max-width: 540px) 100vw, 540px" /></a><figcaption id="caption-attachment-2637" class="wp-caption-text"><span style="font-size: 8pt;">ArrayList</span></figcaption></figure></p>
<p>which as you can see above has the <span style="color: #ff6600;">Add</span> method taking an <span style="color: #ff6600;">object</span> parameter. It means that when we&#8217;d like to add an integer to ArrayList:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212433" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxingarraylist-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="BoxingArrayList.cs content, created by dsibinski on 05:02AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="BoxingArrayList.cs">
<tr>
<td id="file-boxingarraylist-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxingarraylist-cs-LC1" class="blob-code blob-code-inner js-file-line">  ArrayList al = new ArrayList();</td>
</tr>
<tr>
<td id="file-boxingarraylist-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxingarraylist-cs-LC2" class="blob-code blob-code-inner js-file-line">  int i = 8;</td>
</tr>
<tr>
<td id="file-boxingarraylist-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxingarraylist-cs-LC3" class="blob-code blob-code-inner js-file-line">  al.Add(i);</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/976151bb839c107a643e61dc5cab7632/raw/6d96d0a3f37aeb14c32105873e68a772ab1e2490/BoxingArrayList.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/976151bb839c107a643e61dc5cab7632#file-boxingarraylist-cs" class="Link--inTextBlock"><br />
          BoxingArrayList.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>boxing takes place:</p>
<p><figure id="attachment_2638" aria-describedby="caption-attachment-2638" style="width: 768px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2638" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/arraylist_boxingil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?fit=768%2C104&amp;ssl=1" data-orig-size="768,104" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ArrayList_BoxingIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?fit=768%2C104&amp;ssl=1" class="wp-image-2638 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?resize=768%2C104&#038;ssl=1" alt="" width="768" height="104" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?resize=300%2C41&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?resize=720%2C98&amp;ssl=1 720w" sizes="auto, (max-width: 768px) 100vw, 768px" /></a><figcaption id="caption-attachment-2638" class="wp-caption-text"><span style="font-size: 8pt;">ArrayList.Add(int) &#8211; boxing (IL)</span></figcaption></figure></p>
<p>Such issues were eliminated by generics and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=netframework-4.7.2" target="_blank" rel="noopener">generic collections</a>.</p>
<h2>String concatenation</h2>
<p>Another interesting example is the concatenation of strings with value types using &#8220;+&#8221; operator:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212451" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxing_stringconcat-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Boxing_StringConcat.cs content, created by dsibinski on 05:05AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Boxing_StringConcat.cs">
<tr>
<td id="file-boxing_stringconcat-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxing_stringconcat-cs-LC1" class="blob-code blob-code-inner js-file-line">  int i = 8;</td>
</tr>
<tr>
<td id="file-boxing_stringconcat-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxing_stringconcat-cs-LC2" class="blob-code blob-code-inner js-file-line">  string helloText = &quot;Hello&quot;;</td>
</tr>
<tr>
<td id="file-boxing_stringconcat-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxing_stringconcat-cs-LC3" class="blob-code blob-code-inner js-file-line">  string result = helloText + i;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/0f647195dec951e469e6a7476620a4d4/raw/557c22a8c81d8dd985b545feb234a038ff6bd41d/Boxing_StringConcat.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/0f647195dec951e469e6a7476620a4d4#file-boxing_stringconcat-cs" class="Link--inTextBlock"><br />
          Boxing_StringConcat.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Such operation involves <span style="color: #ff6600;">String.Concat</span> <a href="https://msdn.microsoft.com/en-us/library/kbseaaft(v=vs.110).aspx" target="_blank" rel="noopener">method&#8217;s version</a> taking two <span style="color: #ff6600;">object</span> parameters, so it implies boxing the integer first:</p>
<p><figure id="attachment_2639" aria-describedby="caption-attachment-2639" style="width: 626px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2639" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/stringconcatboxingil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?fit=626%2C265&amp;ssl=1" data-orig-size="626,265" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="StringConcatBoxingIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?fit=626%2C265&amp;ssl=1" class="wp-image-2639 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?resize=626%2C265&#038;ssl=1" alt="" width="626" height="265" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?w=626&amp;ssl=1 626w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?resize=300%2C127&amp;ssl=1 300w" sizes="auto, (max-width: 626px) 100vw, 626px" /></a><figcaption id="caption-attachment-2639" class="wp-caption-text"><span style="font-size: 8pt;">String and integer concatenation &#8211; boxing in IL</span></figcaption></figure></p>
<p>In order to avoid it, it&#8217;s enough to slightly modify the code by using <span style="color: #ff6600;">ToString()</span> method on the integer variable (for now ignoring ReSharper telling you it&#8217;s redundant ;)):</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212534" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-stringconcat_withtostring-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="StringConcat_withToString.cs content, created by dsibinski on 05:13AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="StringConcat_withToString.cs">
<tr>
<td id="file-stringconcat_withtostring-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-stringconcat_withtostring-cs-LC1" class="blob-code blob-code-inner js-file-line">  int i = 8;</td>
</tr>
<tr>
<td id="file-stringconcat_withtostring-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-stringconcat_withtostring-cs-LC2" class="blob-code blob-code-inner js-file-line">  string helloText = &quot;Hello&quot;;</td>
</tr>
<tr>
<td id="file-stringconcat_withtostring-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-stringconcat_withtostring-cs-LC3" class="blob-code blob-code-inner js-file-line">  string result = helloText + i.ToString();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/91836b433c4ea1efa9d341f4a323e406/raw/fee89a0895b4aafa5a6a450fb84231dcef14bdb2/StringConcat_withToString.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/91836b433c4ea1efa9d341f4a323e406#file-stringconcat_withtostring-cs" class="Link--inTextBlock"><br />
          StringConcat_withToString.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and there&#8217;s no boxing anymore, as now <span style="color: #ff6600;">String.Concat</span> <a href="https://msdn.microsoft.com/en-us/library/a6d350wd(v=vs.110).aspx" target="_blank" rel="noopener">method&#8217;s version</a> taking two <span style="color: #ff6600;">string</span> parameters is used:</p>
</p>
<p><figure id="attachment_2640" aria-describedby="caption-attachment-2640" style="width: 622px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2640" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/stringconcatnoboxing/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?fit=622%2C273&amp;ssl=1" data-orig-size="622,273" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="StringConcatNoBoxing" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?fit=622%2C273&amp;ssl=1" class="wp-image-2640 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?resize=622%2C273&#038;ssl=1" alt="" width="622" height="273" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?w=622&amp;ssl=1 622w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?resize=300%2C132&amp;ssl=1 300w" sizes="auto, (max-width: 622px) 100vw, 622px" /></a><figcaption id="caption-attachment-2640" class="wp-caption-text"><span style="font-size: 8pt;">String concatenation with <em>ToString</em> usage &#8211; no boxing</span></figcaption></figure></p>
<p>There could be many more cases to present, but the goal is that you get a strong feeling what boxing and unboxing is and when it occurs.</p>
<h1>Performance implications of boxing and unboxing</h1>
<p>As we already know, boxing and unboxing imply some cost. In case of simple stuff like concatenating the string once with some integer, the performance gain by introducing <em>ToString</em> on integer first is unnoticeable. That&#8217;s why, as I wrote before, even ReSharper tells you to not do it:</p>
<p><figure id="attachment_2641" aria-describedby="caption-attachment-2641" style="width: 911px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2641" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/resharper_dontusetostring/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?fit=911%2C126&amp;ssl=1" data-orig-size="911,126" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ReSharper_DontUseToString" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?fit=911%2C126&amp;ssl=1" class="wp-image-2641 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=911%2C126&#038;ssl=1" alt="" width="911" height="126" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?w=911&amp;ssl=1 911w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=300%2C41&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=768%2C106&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=720%2C100&amp;ssl=1 720w" sizes="auto, (max-width: 911px) 100vw, 911px" /></a><figcaption id="caption-attachment-2641" class="wp-caption-text"><span style="font-size: 8pt;">ReSharper &#8211; redundant ToString() call</span></figcaption></figure></p>
<p>In that case it&#8217;s better to keep the clarity of the code without <em>ToString</em> method.</p>
</p>
<p>The perspective changes when you need to perform such operations in a loop for hundreds or thousands times. In this case the execution of code using boxing can be even 150% longer than its equivalent with no boxing (you can create a simple application and measure the execution time of code with and without boxing or check <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types" target="_blank" rel="noopener">this article</a>).</p>
</p>
<p>Boxed values also take more space in the memory than value types stored on the stack. Copying the value to/from the stack is also a cost. According to <a href="https://msdn.microsoft.com/en-us/library/ms173196.aspx" target="_blank" rel="noopener">MSDN</a>, boxing can generally take even 20 times longer that simple reference assignments, whereas unboxing can be 4 times slower than assignments.</p>
<h1>So&#8230; why to use boxing and unboxing?</h1>
<p>Despite all performance implications boxing and unboxing have, these concepts were introduced into .NET because of some reasons:</p>
<ul>
<li>there&#8217;s unified types system in .NET, which allows to &#8220;represent&#8221; both value and reference types in a similar way &#8211; thanks to boxing,</li>
<li>collections could be used for value types before generics were introduced into .NET,</li>
<li>it simplifies our code, like we saw for string concatenation and in most cases this clarity gives us much more than the performance we&#8217;d gain trying to avoid boxing.</li>
</ul>
<p>Boxing and unboxing are so common that we can&#8217;t avoid them. We should be aware how it works in order to be able to minimize their usage, but it should always be considered reasonably. Don&#8217;t spend time on optimizing your code, checking IL all the time to get to the point with the smallest possible number of <span style="color: #ff6600;">box</span> statements used. Keep in mind that the clarity of your code, its self-explanatory structure and comfort of reading is sometimes much more valuable than some small or barely noticeable performance gain.</p>
<h1>Summary</h1>
<p>In today&#8217;s post we saw what is boxing and unboxing, how it&#8217;s represented in the IL code and what implications on performance it may have. I hope it clarifies these commonly mentioned concepts for you, at least a bit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</p>
<p>If you&#8217;re interested in digging into nitty-gritty, low-level details of boxing and unboxing in .NET, I invit<span style="font-size: 1rem;">e you to read </span><a style="background-color: #ffffff; font-size: 1rem;" href="http://mattwarren.org/2017/08/02/A-look-at-the-internals-of-boxing-in-the-CLR/" target="_blank" rel="noopener">this great post by Matt Warren</a><span style="font-size: 1rem;"> about even more internal internals of boxing and unboxing <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></span></p>
</p>
<p>In the next posts <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">in the series</a> we&#8217;re going to start exploring the garbage collection. If you have any suggestions or ideas for the coming articles, let me know in the comments (some of you already did on reddit &#8211; new posts scheduled <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ).</p>
</p>
<p>See you (or better <em>read you</em> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ) next week!</p>
<p>The post <a href="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/">[.NET Internals 03] Boxing and unboxing</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-03-boxing-and-unboxing/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2622</post-id>	</item>
		<item>
		<title>[.NET Internals 02] Stack and heap &#8211;  .NET data structures</title>
		<link>https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/</link>
					<comments>https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 01 Aug 2018 06:00:09 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2576</guid>

					<description><![CDATA[<p>In the second post of .NET Internals series, we&#8217;re going to investigate the organization of .NET process&#8217;s memory. We&#8217;ll see what is stack and heap and what kind of data is stored on each of these memory structures. If you&#8217;re here for the first time, I encourage you to first read the .NET Internals series&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/">[.NET Internals 02] Stack and heap &#8211;  .NET data structures</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the second post of <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a>, we&#8217;re going to investigate the organization of .NET process&#8217;s memory. We&#8217;ll see what is <em>stack</em> and <em>heap</em> and what kind of data is stored on each of these memory structures.<br />
<span id="more-2576"></span></p>
<p>If you&#8217;re here for the first time, I encourage you to first read the .NET Internals series <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">introductory post explaining the basics of memory structure</a>.</p>
<h1>Memory division</h1>
<p>By default, when the .NET application is started and virtual address space is allocated for the process (as we saw in the <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">previous post</a>), the following data structures, represented as <strong>heaps</strong>, are created:</p>
<ul>
<li>Code Heap &#8211; storing <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener" data-wplink-edit="true">JIT-compiled</a> native code,</li>
<li>Small Object Heap (SOH) &#8211; storing objects of size less than 85 kilobytes,</li>
<li>Large Object Heap (LOH) &#8211; storing objects of size greater than 85 kilobytes*,</li>
<li>Process Heap.</li>
</ul>
<p><span style="font-size: 10pt;">*side note: there&#8217;s an exception for arrays of <span style="font-family: terminal, monaco, monospace;">double</span>,  which are allocated on the LOH much before reaching 85K (<span style="font-family: terminal, monaco, monospace;">double[]</span> is considered &#8220;large&#8221; when it exceeds 1000 elements). This is for the sake of 32-bit code optimization. More details <a href="https://stackoverflow.com/questions/8951836/why-large-object-heap-and-why-do-we-care" target="_blank" rel="noopener">here</a> and <a href="https://stackoverflow.com/questions/11791038/large-object-heap-fragmentation-issues-with-arrays" target="_blank" rel="noopener">here</a>.</span></p>
</p>
<p>Division of storing small and large objects on different heaps has its performance reasons, which will be covered in the next posts about garbage collection.</p>
</p>
<p>Elements placed on the heap have their <em>addresses</em>, which are a kind of pointers to the place in memory where the particular object is located.</p>
</p>
<p>Heap is however not the only data structure used by .NET process. There&#8217;s also a <strong>stack</strong>, which helps in tracking code&#8217;s execution and storing some special types of data. We&#8217;ll now see in details how stack and heap are used and organized.</p>
<h1>Stack</h1>
<p><figure id="attachment_2581" aria-describedby="caption-attachment-2581" style="width: 391px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2581" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/stack_wikipedia/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?fit=391%2C281&amp;ssl=1" data-orig-size="391,281" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Stack_Wikipedia" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?fit=391%2C281&amp;ssl=1" class="wp-image-2581 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?resize=391%2C281&#038;ssl=1" alt="" width="391" height="281" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?w=391&amp;ssl=1 391w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?resize=300%2C216&amp;ssl=1 300w" sizes="auto, (max-width: 391px) 100vw, 391px" /></a><figcaption id="caption-attachment-2581" class="wp-caption-text"><span style="font-size: 8pt;">Stack Data Structure, source: Wikipedia</span></figcaption></figure></p>
<p>Stack is a memory structure organized as LIFO (last-in-first-out) collection. If you think about it, it&#8217;s perfect for storing anything that may soon need to be used (easily popped out from the top of the stack). This nature of stack leads to its two main purposes: <strong>keeping track of execution order</strong> and<strong> storing value types variables</strong>.</p>
<h2>Keeping track of execution order &#8211; call stack</h2>
<p>Most of the code we write is wrapped into classes and methods, which can call another methods, which call another methods etc. .NET Framework must all the time keep track of this execution&#8217;s order. Moreover, it also has to remember the state of variables and parameters of the method calling another method, while this another method executes (to be able to restore the calling method&#8217;s state after the called method returns).</p>
</p>
<p>As soon as any method is called, .NET initializes a <em>stack frame</em> (kind of container) which stores all data necessary to execute the method: parameters, local variables and address of the line of code to go back to when the method finishes.  Stack frames are created on the stack on top of each other. Each method has its own stack frame. All that behavior is well illustrated on the figure below.</p>
<p><figure id="attachment_2586" aria-describedby="caption-attachment-2586" style="width: 684px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2586" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/stack_frames_wikipedia/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?fit=684%2C558&amp;ssl=1" data-orig-size="684,558" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Stack_Frames_Wikipedia" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?fit=684%2C558&amp;ssl=1" class="wp-image-2586 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?resize=684%2C558&#038;ssl=1" alt="" width="684" height="558" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?w=684&amp;ssl=1 684w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?resize=300%2C245&amp;ssl=1 300w" sizes="auto, (max-width: 684px) 100vw, 684px" /></a><figcaption id="caption-attachment-2586" class="wp-caption-text">Call stack frames, source: Wikipedia</figcaption></figure></p>
<h3></h3>
<p>Stack used for storing the execution order is often referred to as <strong>call stack, execution stack </strong>or <strong>program stack</strong>.</p>
</p>
<p>Take a look at the following code:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91069473" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-stack_methodsexecutionexample1-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Stack_MethodsExecutionExample1.cs content, created by dsibinski on 08:34PM on July 31, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Stack_MethodsExecutionExample1.cs">
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Method1()</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC3" class="blob-code blob-code-inner js-file-line">      Method2(12);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC4" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(&quot;Goodbye&quot;);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC6" class="blob-code blob-code-inner js-file-line">  void Method2(int testData)</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC7" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC8" class="blob-code blob-code-inner js-file-line">      int multiplier = 2;</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC9" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(&quot;Value is &quot; + testData);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC10" class="blob-code blob-code-inner js-file-line">      Method3(testData* multiplier);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC11" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC12" class="blob-code blob-code-inner js-file-line">  void Method3(int data)</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC13" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC14" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(&quot;Double &quot; + data);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC15" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC16" class="blob-code blob-code-inner js-file-line">// source: C. Farrell and N. Harrison &#8211; Under the Hood of .NET Memory Management</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/d21ce0c0fe4fb65cec0739fa18980944/raw/e58ac87fc596034e2263edcfa0586bfeebf6752c/Stack_MethodsExecutionExample1.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/d21ce0c0fe4fb65cec0739fa18980944#file-stack_methodsexecutionexample1-cs" class="Link--inTextBlock"><br />
          Stack_MethodsExecutionExample1.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In order to call <span style="font-family: terminal, monaco, monospace;">Method2</span>, the framework must save an execution return address which will be the next line of code to execute after <span style="font-family: terminal, monaco, monospace;">Method2</span> finishes (line 4 in the example above). This address altogether with parameters and local variables of the calling and called methods are stored on the call stack, as the schema below presents.</p>
</p>
<p><figure id="attachment_2588" aria-describedby="caption-attachment-2588" style="width: 421px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2588" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/executionstack1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?fit=421%2C274&amp;ssl=1" data-orig-size="421,274" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ExecutionStack1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?fit=421%2C274&amp;ssl=1" class="wp-image-2588 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?resize=421%2C274&#038;ssl=1" alt="" width="421" height="274" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?w=421&amp;ssl=1 421w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?resize=300%2C195&amp;ssl=1 300w" sizes="auto, (max-width: 421px) 100vw, 421px" /></a><figcaption id="caption-attachment-2588" class="wp-caption-text"><span style="font-size: 8pt;">Call stack for methods 1-3, source: C. Farrell and N. Harrison &#8211; <em>Under the Hood of .NET Memory Management</em></span></figcaption></figure></p>
<p>You can also notice what happens when <span style="font-family: terminal, monaco, monospace;">Method3</span> returns (its stack frame is popped out from the stack &#8211; it disappears).</p>
<h2>Storing value types</h2>
<p>Stack is also used to store variables of any of .NET value types, including <span style="font-family: terminal, monaco, monospace;">bool</span>, <span style="font-family: terminal, monaco, monospace;">decimal</span>, <span style="font-family: terminal, monaco, monospace;">int</span> etc. Full list of .NET value types can be found <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types-table" target="_blank" rel="noopener">here</a>.</p>
</p>
<p>Value types are basically the types which keep the data and memory in the same location. What&#8217;s also interesting to know is that all value-typed local variables of the method allocated on the stack are cleaned-up after the method&#8217;s execution finishes. It happens because the method&#8217;s stack frame becomes unreachable &#8211; stack has some pointer to the beginning of the top-level stack frame (<em>current</em> stack frame pointer), which is simply moved to the second stack frame from the top as soon as the method&#8217;s execution is finished (the data is still physically there, but it&#8217;s not reachable by default .NET mechanisms).</p>
<h1>Heap</h1>
<p>Heap is similar to stack, but if the stack can be imagined as a series of boxes stacked on top of each other, where we always push or pop the top one, heap contains boxes that can be accessed at any time. The boxes in the heap are placed in different places, not necessarily on the top of each other. To access one of the boxes we don&#8217;t need to pop out the top ones first.</p>
<h2>Storing reference types</h2>
<p>All other variables, which are not value types i.e. are either <span style="font-family: terminal, monaco, monospace;">string</span> or <span style="font-family: terminal, monaco, monospace;">object</span> (or deriving from one of these, so all classes, interfaces and delegates) are referred to as <strong>reference types</strong>. All reference types are allocated on the managed heap (SOH or LOH, depending on their size). However, even though an object is allocated on the heap, a <em>reference</em> to it (address on the heap) is stored on the stack.</p>
</p>
<p>Consider the following code:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91069943" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-heap_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Heap_example.cs content, created by dsibinski on 09:03PM on July 31, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Heap_example.cs">
<tr>
<td id="file-heap_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-heap_example-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Method1()</td>
</tr>
<tr>
<td id="file-heap_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-heap_example-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-heap_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-heap_example-cs-LC3" class="blob-code blob-code-inner js-file-line">      MyClass myObj = new MyClass();</td>
</tr>
<tr>
<td id="file-heap_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-heap_example-cs-LC4" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(myObj.ToString());</td>
</tr>
<tr>
<td id="file-heap_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-heap_example-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/68ad6011969b6f0105ce680d42b0aab5/raw/374167390f346a64c2649ef2a0b60632d56a1585/Heap_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/68ad6011969b6f0105ce680d42b0aab5#file-heap_example-cs" class="Link--inTextBlock"><br />
          Heap_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>The figure below presents how stack and heap would look like here in terms of allocated data:</p>
<p><figure id="attachment_2590" aria-describedby="caption-attachment-2590" style="width: 1011px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2590" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/heap/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?fit=1011%2C498&amp;ssl=1" data-orig-size="1011,498" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Heap" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?fit=1011%2C498&amp;ssl=1" class="wp-image-2590 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=1011%2C498&#038;ssl=1" alt="" width="1011" height="498" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?w=1011&amp;ssl=1 1011w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=300%2C148&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=768%2C378&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=720%2C355&amp;ssl=1 720w" sizes="auto, (max-width: 1011px) 100vw, 1011px" /></a><figcaption id="caption-attachment-2590" class="wp-caption-text"><span style="font-size: 8pt;">Stack and Heap with reference variable, source: C. Farrell and N. Harrison &#8211; <em>Under the Hood of .NET Memory Management</em></span></figcaption></figure></p>
<p>The &#8220;OBJREF&#8221; stored on the stack is actually a pointer (reference) to the <span style="font-family: terminal, monaco, monospace;">MyClass</span> object on the heap.</p>
</p>
<p>NOTE:  <span style="font-family: terminal, monaco, monospace; color: #ff6600;">MyClass myObj</span> statement doesn&#8217;t allocate any space on the heap for <span style="font-family: terminal, monaco, monospace;">myObj</span> variable. It only creates &#8220;OBJREF&#8221; variable on the stack, initializing it with <span style="color: #ff6600;">NULL</span> value. By the time <span style="color: #ff6600;">new</span> statement is used, the actual memory allocation on the heap takes place and the reference&#8217;s value is set.</p>
<h1>Value types vs reference types (stack vs heap)</h1>
<p>The crucial difference between value and reference types is that when a <strong>value type</strong> variable is passed to another method as parameter or just assigned to another value type variable, its value is <strong>copied into the new variable</strong>. That&#8217;s why when passing a value type to another method, which modifies this variable (parameter), when the method returns the original variable&#8217;s value is not changed (it was its copy which was used inside the called method). Figure below shows this behavior.</p>
<p><figure id="attachment_2593" aria-describedby="caption-attachment-2593" style="width: 616px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2593" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/valuetypescopy/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?fit=616%2C276&amp;ssl=1" data-orig-size="616,276" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ValueTypesCopy" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?fit=616%2C276&amp;ssl=1" class="wp-image-2593 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?resize=616%2C276&#038;ssl=1" alt="" width="616" height="276" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?w=616&amp;ssl=1 616w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?resize=300%2C134&amp;ssl=1 300w" sizes="auto, (max-width: 616px) 100vw, 616px" /></a><figcaption id="caption-attachment-2593" class="wp-caption-text"><span style="font-size: 8pt;">Value types copying, source: <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types" target="_blank" rel="noopener">link</a></span></figcaption></figure></p>
<p>It&#8217;s different in case of reference types. When reference type variable is assigned to another <strong>reference type</strong> variable (or method&#8217;s parameter), <strong>it&#8217;s not its value which is copied, but only the</strong> <strong>reference</strong> to it (address in the memory where the data is actually stored on the heap). In effect, the new variable (or method&#8217;s parameter) still points to the same place in memory, so modifying such reference type variable inside the called method will also be in effect outside of the method. This case is illustrated below.</p>
<p><figure id="attachment_2594" aria-describedby="caption-attachment-2594" style="width: 616px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2594" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/referencescopying/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?fit=616%2C331&amp;ssl=1" data-orig-size="616,331" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ReferencesCopying" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?fit=616%2C331&amp;ssl=1" class="wp-image-2594 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?resize=616%2C331&#038;ssl=1" alt="" width="616" height="331" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?w=616&amp;ssl=1 616w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?resize=300%2C161&amp;ssl=1 300w" sizes="auto, (max-width: 616px) 100vw, 616px" /></a><figcaption id="caption-attachment-2594" class="wp-caption-text"><span style="font-size: 8pt;">References passing, source: <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types" target="_blank" rel="noopener">link</a></span></figcaption></figure></p>
<p>Of course, storing some data on the stack and some on the heap (moreover: different types of heaps) has its precise purpose, which we&#8217;re going to explore in the coming posts <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Summary</h1>
<p>In today&#8217;s post we went through stack and heap, two data structures used for storing value and reference types and tracking execution order of .NET application. In the next posts <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">in the series</a> we will see what is <em>boxing</em> and <em>unboxing</em> and how it can affect application&#8217;s performance. We will also examine the <em>garbage collection</em> process in details.</p>
</p>
<p>Stay tuned!</p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-5" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1779348823" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-5" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/">[.NET Internals 02] Stack and heap &#8211;  .NET data structures</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2576</post-id>	</item>
		<item>
		<title>[.NET Internals 01] Basics of memory structure</title>
		<link>https://www.codejourney.net/net-internals-01-basics-of-memory-structure/</link>
					<comments>https://www.codejourney.net/net-internals-01-basics-of-memory-structure/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 25 Jul 2018 06:00:52 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2523</guid>

					<description><![CDATA[<p>Have you ever wondered about what&#8217;s under the hood of the applications you develop? Ever been surprised that there&#8217;s no need to worry about memory allocation and deallocation using high-level programming languages such as Java or C# after leaving the university* ? Still remember (old) C++ times with delete statement? By this post, I&#8217;d like to&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/">[.NET Internals 01] Basics of memory structure</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever wondered about what&#8217;s under the hood of the applications you develop?</p>
<p>Ever been surprised that there&#8217;s no need to worry about memory allocation and deallocation using high-level programming languages such as Java or C# after leaving the university<strong>* </strong>?</p>
</p>
<p>Still remember (old) C++ times with <span style="color: #ff6600;">delete</span> statement?</p>
<h1></h1>
<p><figure id="attachment_2524" aria-describedby="caption-attachment-2524" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2524" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/cpp_pointers_meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?fit=470%2C414&amp;ssl=1" data-orig-size="470,414" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="CPP_Pointers_Meme" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?fit=470%2C414&amp;ssl=1" class="wp-image-2524 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?resize=300%2C264&#038;ssl=1" alt="" width="300" height="264" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?resize=300%2C264&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?w=470&amp;ssl=1 470w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2524" class="wp-caption-text"><span style="font-size: 8pt;">Source: &#8220;Arnaud Porterie &#8211; The Truth About C++&#8221;</span></figcaption></figure></p>
<p>By this post, I&#8217;d like to introduce a new &#8220;.NET Internals&#8221; series on the blog. I will be publishing a <strong>new post on .NET internal concepts every Wednesday. </strong>No end date for the moment <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2523"></span></p>
<p>Posts within the series will be mostly about memory management and performance aspects of .NET applications. All discussed concepts are applicable to most of the modern programming platforms, but the examples will be based on .NET Framework.</p>
</p>
<p>If you&#8217;re interested in such topics, I encourage you to check this blog every Wednesday starting today <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</p>
<p><span style="font-size: 8pt;"><strong>*</strong>there is <strong>1 assumption</strong> and <strong>1 fact</strong> here:</span></p>
<ul>
<li><span style="font-size: 8pt;"><strong>assumption</strong>: you used to program in C/C++ (before C++11) on the university,</span></li>
<li><span style="font-size: 8pt;"><strong>fact</strong>: that&#8217;s not true you don&#8217;t need to worry about memory management using high-level programming languages; wait for the next posts to get to know why.</span></li>
</ul>
<h1></h1>
<h1>CLR</h1>
<p>Each application targeting .NET is managed by CLR (<em>Common Language Runtime</em>), which is a part of .NET Framework, which must be installed on the computer on which the .NET application is launched &#8211; the exception are <a href="https://docs.microsoft.com/en-us/dotnet/core/deploying/#self-contained-deployments-scd" target="_blank" rel="noopener">.NET Core self-contained apps</a>, which we are not discussing in this series. By default, the CLR is loaded by each .NET process as a hosted process (so the CLR runs as a part of .NET application).</p>
</p>
<p>This CLR &#8220;layer&#8221; is responsible for various things while our application is running:</p>
<ul>
<li>executing CIL (<em>Common Intermediate Language</em>),</li>
<li>ensuring type safety,</li>
<li>handling exceptions,</li>
<li>managing threads,</li>
<li>garbage collection.</li>
</ul>
<h1>Memory structure</h1>
<p>Already running application is represented as a <em>process</em> in the operating system. As software developers we know that such process saves some data into the memory, which is determined by the amount of RAM available on the computer. However, process never operates on this &#8220;open memory&#8221; &#8211; only OS has direct access to it. When the CLR is launched within .NET process, it requests some amount of RAM from the operating system. This memory chunk is called <strong><em>virtual address space</em></strong>. Each process has its own virtual address space, but <strong>all processes running on the same machine share the same physical memory</strong>.</p>
<h2>32-bit OS</h2>
<p>Do you remember 32-bit editions of Windows XP, which could only use 4GBs of RAM (with <a href="https://superuser.com/questions/27086/why-does-windows-only-show-about-3-5-gb-of-my-4-gb-of-ram" target="_blank" rel="noopener">even less visible to the user</a>)? The reason for that is that <strong>in 32-bit operating systems total virtual address space is 4GBs</strong>, usually divided into two equal chunks &#8211; first one owned by the OS and the second one prepared for user processes. The diagram below presents.</p>
<p><figure id="attachment_2542" aria-describedby="caption-attachment-2542" style="width: 268px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2542" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/system_process_vas_32/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?fit=268%2C267&amp;ssl=1" data-orig-size="268,267" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="System_process_VAS_32" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?fit=268%2C267&amp;ssl=1" class="wp-image-2542 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?resize=268%2C267&#038;ssl=1" alt="" width="268" height="267" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?w=268&amp;ssl=1 268w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?resize=150%2C150&amp;ssl=1 150w" sizes="auto, (max-width: 268px) 100vw, 268px" /></a><figcaption id="caption-attachment-2542" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces</a></span></figcaption></figure></p>
<h2>64-bit OS</h2>
<p>In 64-bit Windows theoretical amount of virtual address space is 16 exabytes (2<sup>64</sup> bytes). In reality, only a part of it is used: 8-terabyte chunk is used for user space and portions of 248-terabyte are used for the OS:</p>
<p><figure id="attachment_2544" aria-describedby="caption-attachment-2544" style="width: 227px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2544" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/system_process_vas_64/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?fit=227%2C329&amp;ssl=1" data-orig-size="227,329" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="System_process_VAS_64" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?fit=227%2C329&amp;ssl=1" class="wp-image-2544 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?resize=227%2C329&#038;ssl=1" alt="" width="227" height="329" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?w=227&amp;ssl=1 227w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?resize=207%2C300&amp;ssl=1 207w" sizes="auto, (max-width: 227px) 100vw, 227px" /></a><figcaption id="caption-attachment-2544" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces</a></span></figcaption></figure></p>
<h2>Sharing memory between processes</h2>
<p>What seems to be critical to understand is how this whole <strong>virtual memory is shared between processes</strong>. As we said before, multiple processes share the same memory, but accessing different (separate) chunks of it. Let us illustrate once more:</p>
<p><figure id="attachment_2545" aria-describedby="caption-attachment-2545" style="width: 399px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2545" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/processessharingmemory/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?fit=399%2C364&amp;ssl=1" data-orig-size="399,364" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ProcessesSharingMemory" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?fit=399%2C364&amp;ssl=1" class="wp-image-2545 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?resize=399%2C364&#038;ssl=1" alt="" width="399" height="364" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?w=399&amp;ssl=1 399w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?resize=300%2C274&amp;ssl=1 300w" sizes="auto, (max-width: 399px) 100vw, 399px" /></a><figcaption id="caption-attachment-2545" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces</a></span></figcaption></figure></p>
<p>As can be seen, <strong>each process reserves different <em>pages</em> of memory when it&#8217;s needed</strong>. Even though the default 2GBs of virtual memory reserved for a single process may seem to be a lot, every developer needs to be aware that <strong>when an <em>allocation </em>(reservation of memory chunk) is made</strong> (manually or by memory management system) the <strong>virtual memory manager needs to find a single, continuous virtual memory block</strong> large enough to store the requested amount of data. This rule leads to the presence of &#8220;holes&#8221; in the memory. This virtual memory <em>fragmentation</em> is well-presented on the diagram below:</p>
<p><figure id="attachment_2546" aria-describedby="caption-attachment-2546" style="width: 138px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2546" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/virtualmemoryfragmentation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" data-orig-size="138,305" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="VirtualMemoryFragmentation" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" class="wp-image-2546 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=138%2C305&#038;ssl=1" alt="" width="138" height="305" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?w=138&amp;ssl=1 138w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=136%2C300&amp;ssl=1 136w" sizes="auto, (max-width: 138px) 100vw, 138px" /></a><figcaption id="caption-attachment-2546" class="wp-caption-text"><span style="font-size: 8pt;">Virtual memory fragmentation</span></figcaption></figure></p>
<p>However, this requirement of finding a continuous block to be allocated refers only to the virtual memory. Physical memory is divided into pages, which can be stored in totally different places &#8211; as you can see on the diagram above with Notepad.exe application using continuous blocks of its virtual memory, but <a href="https://docs.microsoft.com/en-us/windows/desktop/memory/reserving-and-committing-memory" target="_blank" rel="noopener"><em>committed</em></a> to noncontiguous pages scattered in various physical locations.</p>
</p>
<p>If the process requests for too much memory, which cannot be continuously allocated in the virtual address space (your process is out of virtual memory) or no more virtual memory can be committed (assigned) to the physical storage, it can result in <span style="color: #ff6600;">OutOfMemoryException</span> thrown by .NET code.</p>
<h1>Summary</h1>
<p>This was the introductory post of my new <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a>. We saw what are the basic concepts of the memory structure, learnt what is virtual address space, how physical memory is shared between processes and why Windows XP was able to handle only 4GBs of RAM <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</p>
<p>See you next Wednesday!</p>
</p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-6" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1779348823" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-6" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/">[.NET Internals 01] Basics of memory structure</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-01-basics-of-memory-structure/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2523</post-id>	</item>
		<item>
		<title>GET.NET 2018 &#8211; Łódź edition</title>
		<link>https://www.codejourney.net/get-net-2018-lodz-edition/</link>
					<comments>https://www.codejourney.net/get-net-2018-lodz-edition/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 17 Apr 2018 19:57:57 +0000</pubDate>
				<category><![CDATA[Conferences]]></category>
		<category><![CDATA[.NET]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2462</guid>

					<description><![CDATA[<p>On 14.04.2018 I attended GET.NET conference in Łódź. It offers two editions &#8211; the spring one held in Łódź and the autumn one held in Gdańsk. In today&#8217;s post I&#8217;m going to sum up the conference and the sessions I attended 🙂 Tickets and organization I attended the same conference 2 years ago and that&#8230;</p>
<p>The post <a href="https://www.codejourney.net/get-net-2018-lodz-edition/">GET.NET 2018 &#8211; Łódź edition</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>On 14.04.2018 I attended <a href="https://konferencjaget.net" target="_blank" rel="noopener">GET.NET</a> conference in Łódź. It offers two editions &#8211; the spring one <a href="https://konferencjaget.net/en/lodz" target="_blank" rel="noopener">held in Łódź</a> and the autumn one <a href="https://konferencjaget.net/en/gdansk" target="_blank" rel="noopener">held in Gdańsk.</a></p>
<p>In today&#8217;s post I&#8217;m going to sum up the conference and the sessions I attended <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2462"></span></p>
<p><figure id="attachment_2470" aria-describedby="caption-attachment-2470" style="width: 169px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2470" data-permalink="https://www.codejourney.net/get-net-2018-lodz-edition/getnetconferencebadge/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?fit=2608%2C4632&amp;ssl=1" data-orig-size="2608,4632" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1523694247&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;536&quot;,&quot;shutter_speed&quot;:&quot;0.029996322450868&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="GetNetConferenceBadge" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?fit=577%2C1024&amp;ssl=1" class="wp-image-2470 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?resize=169%2C300&#038;ssl=1" alt="" width="169" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?resize=768%2C1364&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?resize=577%2C1024&amp;ssl=1 577w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?resize=720%2C1279&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/GetNetConferenceBadge.jpg?w=2280&amp;ssl=1 2280w" sizes="auto, (max-width: 169px) 100vw, 169px" /></a><figcaption id="caption-attachment-2470" class="wp-caption-text">GET.NET 2018 &#8211; conference&#8217;s badge</figcaption></figure></p>
<h1>Tickets and organization</h1>
<p>I attended the same conference 2 years ago and that time the conference was free. This year (I don&#8217;t know how it was organized last year) the tickets were paid. Normal ticket costed 150 PLN (~45 USD). The organizers also offered tickets for students for 50 PLN (~ 15 USD). This shows that the entrance was rather cheap as for such a full-day event, also compared to some similar conferences held in Poland.</p>
<p>In my opinion, making the conference paid improved the event in general. I felt the talks were generally more concrete, given by some well-known speakers (also abroad ones). The whole event seemed to be more &#8220;cosy&#8221; than 2 years ago. There were less people, at least I felt so (not knowing the real numbers).</p>
<p>This year, the conference was held at <a href="https://www.centrumdialogu.com/en" target="_blank" rel="noopener"><em>Marek Edelman Dialogue Center</em></a> in Łódź:</p>
<p><figure id="attachment_2464" aria-describedby="caption-attachment-2464" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2464" data-permalink="https://www.codejourney.net/get-net-2018-lodz-edition/marekedelmancenter/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1523711958&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;100&quot;,&quot;shutter_speed&quot;:&quot;0.00066188635528963&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MarekEdelmanCenter" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2464 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/04/MarekEdelmanCenter.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2464" class="wp-caption-text">Marek Edelman Center (Łódź) &#8211; GET.NET 2018&#8217;s venue</figcaption></figure></p>
<p>The place was OK in general, with two rooms in which the presentations were done &#8211; one downstairs, the other upstairs. The building is quite spatial and comfortable and in a good location.</p>
<p>There was just one downside of this venue &#8211; there turned out to be not enough places to eat. The stand-up tables were OK during the coffee breaks, but it turned out to be insufficient during lunch. All attendees started to take their plates and eat, but there were no places to sit down. It was quite difficult to eat in such conditions, so there&#8217;s a place to improve here. But come on, that&#8217;s not food what we came there for, right? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Sessions</h1>
<p>Below I&#8217;m listing and describing my subjective feelings on the sessions I chose to attend from two simultaneous tracks available. The sessions included both Polish and English ones (in the schedule there was always at least one English session to choose at a time).</p>
<h2>Mark Rendle &#8211; Cloud Native .NET</h2>
<p>First presentation of the day, the opening keynote, was held by <a href="https://twitter.com/markrendle" target="_blank" rel="noopener">Mark Rendle</a>. The title of his talk was &#8220;Cloud Native .NET&#8221;. Mark explained us what the &#8220;Cloud Native&#8221; actually means, mentioning and digging into concepts of microservices and Kubernetes. During the talk Mark was using the presentation system he implemented, which is <a href="https://slidable.io/" target="_blank" rel="noopener">slidable.io</a>. What&#8217;s interesting, the system allowed to ask questions directly from mobile devices and few folks made use of this functionality <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>All examples and concepts Mark presented during his talk are available in the <a href="https://github.com/slidable/" target="_blank" rel="noopener">source code of Slidable</a>, which can be treated as a reference for building web application in accordance with &#8220;Cloud Native&#8221; and its principles.</p>
<h2>Tomasz Onyszko &#8211; application + cloud + security =&gt; what could go wrong!</h2>
<p>I was a bit disappointed when I entered the room in which <a href="https://twitter.com/tonyszko" target="_blank" rel="noopener">Tomasz</a>&#8216;s presentation took place, as the presenter made the disclaimer in the very beginning that we will see a lot of Azure during the talk. For the last 2-3 years I&#8217;ve seen too much of Azure on various conferences and meetups so I&#8217;m a bit fed up with it. Maybe it&#8217;s only my personal feeling, but I think that Azure is very fancy and extremely helpful for developers, but it&#8217;s not a thing that you can start playing with directly after the conference. Most of the services are paid and for sure worth their prices in an enterprise, but not easy to start working with on a development playground after work. I really like to see some sneak peaks of trendy technology or interesting aspects that I could focus on in software development, but I didn&#8217;t feel getting it after this talk.</p>
<p>The presentation showed few mostly authentication and security-related functionalities in Azure, which are for sure useful for administrators working on machines&#8217; configuration. I didn&#8217;t really feel like I learnt something new and useful during the talk, however the presenter was very good and with a nice sense of humor, so for people interested in such topics and working with Azure on a daily basis I&#8217;d definitely recommend this session.</p>
<h2>Rafał Legiędź &#8211; developing for mixed reality with Hololens</h2>
<p>For me, <a href="https://twitter.com/rafek" target="_blank" rel="noopener">Rafał</a>&#8216;s talk was the best one on the whole conference. He presented us with the basics of <a href="https://www.microsoft.com/en-us/hololens" target="_blank" rel="noopener">Hololens</a>, including basic technical and construction details of the device and the most common usage cases of it. First of all, I was surprised that in contrary to popular belief devices like Hololens and not used mostly for having fun or playing games. It&#8217;s used for things like <a href="https://www.youtube.com/watch?v=8OWhGiyR4Ns" target="_blank" rel="noopener">elevator maintenance</a> or <a href="https://www.youtube.com/watch?v=3QyA7HhIYkg" target="_blank" rel="noopener">cars design and production process</a>.</p>
<p>The presenter defined the two popular terms: VR (v<em>irtual reality</em>) and AR (a<em>ugmented reality</em>) emphasising the difference between them. By the end of the talk, Rafał showed us how easy it is to start developing for Hololens with Unity and Visual Studio.</p>
<p>The topic of AR devices is very inspiring and seems to be developing rapidly. On the other hand, there are already a lot of real, deployed solutions that help manufacturing or banking corporations to build their products more effectively, which I was not aware of. I think this topic is really a future and will be an important piece of software development in the upcoming years, even though it may seem a niche for the moment. I really recommend everyone to get into the topic, even it may not be affordable for everyone &#8211; the cheapest, development Hololens set with no guarantee costs 3000$. However, there are some cheaper AR glasses slowly appearing on the market (can be bought for even 900-1000$), so it should become more available in the coming years. Nevertheless the topic is worth attention, as this technological stack is a completely different world, offering totally different possibilities than &#8220;casual&#8221; software.</p>
<h2>Matthias Koch &#8211; become a productive .NET developer with JetBrains Rider</h2>
<p>First presentation after the lunch break I decided to attend was done by <a href="http://ithrowexceptions.com/about/" target="_blank" rel="noopener">Matthias Koch</a> &#8211; a developer working for <a href="https://www.jetbrains.com/" target="_blank" rel="noopener">JetBrains</a> on a cross-platform <a href="https://www.jetbrains.com/rider/" target="_blank" rel="noopener">Rider IDE</a> for .NET. Although the talk was very lively done, it was a step-by-step presentation of functionalities coming from <a href="https://www.jetbrains.com/resharper/" target="_blank" rel="noopener">ReSharper</a> introduced into the Rider UI. I use ReSharper on daily basis so I knew most of the functionalities, however I learnt some new and useful ones <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Apart from that, the Rider IDE didn&#8217;t seem anything special itself. Apart from being cross-platform I didn&#8217;t notice any big difference between using Rider or Visual Studio with ReSharper (assuming you work on Windows). Matthias mentioned that as Rider is based on JVM, the garbage collection is more effective than in VS, as it doesn&#8217;t need to stop all of the working threads during the collection cycle. Maybe it improves the performance of the IDE in some extent.</p>
<h2>Michał Bartyzel &#8211; please, motivate me!</h2>
<p>The talk by <a href="https://twitter.com/MichalBartyzel" target="_blank" rel="noopener">Michał Bartyzel</a> was the one non-technical with a hope to get some new ideas of self-development or productivity. It was generally well-done, with the good sense of humor from the presenter included. Michał presented some set of non-obvious recommendations to get ourselves self-motivated including sleeping well, not being hungry when making important decisions or creation of non-TODO-lists. Some of the techniques he mentioned are familiar to me as you could read in <a href="https://www.codejourney.net/2017/03/simple-habits-for-better-productivity/" target="_blank" rel="noopener">my post about productivity</a>.</p>
<p>Basically, Michał gave us some easy tips than can be extremely helpful in self-organization. Such recommendations may sound obvious and not worth attention, but I really recommend at least trying to introduce some of them &#8211; it really helps. Michał published the slides from his presentation (Polish only) <a href="https://drive.google.com/file/d/1U2niFmE1f527QwoNmF3vN9_P3InoBXDq/view" target="_blank" rel="noopener">here</a>.</p>
<h2>Ian Cooper &#8211; 12-Factor apps</h2>
<p>The closing talk was done by <a href="https://twitter.com/ICooper" target="_blank" rel="noopener">Ian Cooper</a>, software development geek coming from London and being in the programming industry for quite a few years <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The talk was concerning the concept of &#8220;12-Factor apps&#8221;, which is basically a set of principles that every modern, &#8220;cloud native&#8221; application should follow. Ian focused on few most important of these rules and showed us some code presenting these concepts. More details about 12 factors can be read on <a href="https://12factor.net/" target="_blank" rel="noopener">https://12factor.net/</a></p>
<p>The whole idea is definitely worth knowing, especially in the modern world when the web applications are required to be build in <em>software-as-a-service</em> approach. I think it was a very good, <em>meaty</em> summary of the day, encapsulating concepts that are currently very <em>trendy</em> and asked by the business. The <em>Twelve-Factor App</em> concept can be seen as a guide to build reliable, extensible and loosely-coupled software with low entry threshold for new developers. With the power of cloud and computation centers like Azure, which is now mentioned during almost every presentation :), I see it as a crucial set of principles to follow to be able to use the power of hardware we have (powered by robust software), to produce high-quality and scalable IT systems and applications.</p>
<h1>Summary</h1>
<p>To sum up, the conference was very good. It felt to be small, family-atmosphere conference with not thousands of attendees. The talks were generally high-quality. Even if some I decided to attend were not especially interesting for me, I&#8217;m sure these ones provided great value for people being really into the covered topics.</p>
<p>I definitely recommend the conference to all .NET (and not only!) developers and will surely attend again <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/get-net-2018-lodz-edition/">GET.NET 2018 &#8211; Łódź edition</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/get-net-2018-lodz-edition/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2462</post-id>	</item>
		<item>
		<title>.NET Developer Days 2017</title>
		<link>https://www.codejourney.net/net-developer-days-2017/</link>
					<comments>https://www.codejourney.net/net-developer-days-2017/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 21 Oct 2017 12:17:50 +0000</pubDate>
				<category><![CDATA[Conferences]]></category>
		<category><![CDATA[.NET]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2381</guid>

					<description><![CDATA[<p>On 18-20.10.2017 I had a pleasure to attend .NET Developer Days 2017 conference in Warsaw. The first day we took part in a full-day workshop on containers with Docker and the next two days we attended the conference itself. In this post I&#8217;d like to share my thoughts and insights on the conference, its organizational&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-developer-days-2017/">.NET Developer Days 2017</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div>On 18-20.10.2017 I had a pleasure to attend .NET Developer Days 2017 conference in Warsaw. The first day we took part in a full-day workshop on containers with Docker and the next two days we attended the conference itself. In this post I&#8217;d like to share my thoughts and insights on the conference, its organizational aspects as well as my subjective opinions on the sessions I attended.</p>
</div>
<p><span id="more-2381"></span></p>
<div> </div>
<div>Let me start by describing the workshops and all sessions I was present at. You can find the list of all sessions that were held during the conference <a href="http://net.developerdays.pl/" target="_blank" rel="noopener">on its official website</a>.</div>
<div> </div>
<h2>Day 1 &#8211; workshops</h2>
<h5><em>Breaking Apps Apart Intentionally &#8211; Visual Studio + Docker + Sprinkles of Azure = Modern Microservices</em> (<a href="https://twitter.com/mangalexandru" target="_blank" rel="noopener">Alex Mang</a>)</h5>
<div>As I mentioned before, .NET Developer Days offers pre-cons as a full-day workshop. We chose above-mentioned workshop hosted by Alex Mang:</div>
<div>
<figure id="attachment_2382" aria-describedby="caption-attachment-2382" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2382" data-permalink="https://www.codejourney.net/net-developer-days-2017/01_workshop/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508317278&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;636&quot;,&quot;shutter_speed&quot;:&quot;0.020003678276361&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="01_WorkShop" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2382 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/01_WorkShop.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2382" class="wp-caption-text">Docker workshop with Alex Mang</figcaption></figure></p>
<div>Here I need to mention one organizational drawback &#8211; we didn&#8217;t have any desks in the workshop&#8217;s room, which was quite uncomfortable &#8211; it&#8217;s always better to be able to have your laptop on the desk in front of you in order to write down some stuff or test things covered by the speaker. It was surprising as in the other rooms where the rest of workshop sessions were held the desks were present.</p>
</div>
<div> </div>
<div>That is however the only dark side of this workshop. Alex hosted a very good session, explaining the containers concept using <a href="https://www.docker.com/" target="_blank" rel="noopener">Docker</a>, <a href="https://hub.docker.com/" target="_blank" rel="noopener">DockerHub</a>, Visual Studio and Microsoft Azure. Maybe in the beginning the session was too &#8220;slidy&#8221; with a lot of architectural diagrams, but fortunately around the middle of workshop Alex switched to VS and PowerShell showing us several fancy features of Docker:</div>
<div>
<figure style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2383" data-permalink="https://www.codejourney.net/net-developer-days-2017/02_workshop_powershelldocker/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508328657&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;548&quot;,&quot;shutter_speed&quot;:&quot;0.020003676275626&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="02_WorkShop_PowerShellDocker" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2383 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/02_WorkShop_PowerShellDocker.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption class="wp-caption-text">Docker in PowerShell</figcaption></figure></p>
<h2>Day 2 &#8211; conference 1st day</h2>
<h5><em> 5 unit testing facts I wish I know 10 years ago (<a href="https://twitter.com/dhelper" target="_blank" rel="noopener">Dror Helper</a>)</em></h5>
<p><figure id="attachment_2387" aria-describedby="caption-attachment-2387" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2387" data-permalink="https://www.codejourney.net/net-developer-days-2017/05_drophelper_5unittestsfacts/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508409743&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;788&quot;,&quot;shutter_speed&quot;:&quot;0.079996326568684&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="05_DropHelper_5UnitTestsFacts" data-image-description="" data-image-caption="&lt;p&gt;Dror Helper&amp;#8217;s session on Unit Tests&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2387 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/05_DropHelper_5UnitTestsFacts.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2387" class="wp-caption-text">Dror Helper&#8217;s session on Unit Tests</figcaption></figure></p>
<div>The session&#8217;s difficulty level was defined as 200, which means it&#8217;s an &#8220;easy&#8221; one, however I really enjoyed it. Dror showed some basic, but very important concepts needed to start writing unit tests. Maybe it&#8217;s even more accurate to say he <strong>eliminated all of the most common excuses a lot of us (programmers) have to not write unit tests</strong>. Very important knowledge so to say <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<div>Slides were very good quality and the speaker himself is quite a funny guy <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f603.png" alt="😃" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
</div>
</div>
<h5><em> How Far Can &#8216;Serverless&#8217; Actually Go? </em>(<a href="https://twitter.com/mangalexandru" target="_blank" rel="noopener">Alex Mang</a>)</h5>
<p><figure id="attachment_2388" aria-describedby="caption-attachment-2388" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2388" data-permalink="https://www.codejourney.net/net-developer-days-2017/06_alexmang/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508414435&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;786&quot;,&quot;shutter_speed&quot;:&quot;0.0499999975&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="06_AlexMang" data-image-description="" data-image-caption="&lt;p&gt;Alex Mang on stage&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2388 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/06_AlexMang.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2388" class="wp-caption-text">Alex Mang on stage</figcaption></figure></p>
<div>
<div>Alex is a kind of guy I like &#8211; a bit american-styled speaker with appropriate sense of humor. During the session he explained and showed how to build an application using <a href="https://azure.microsoft.com/en-us/services/functions/" target="_blank" rel="noopener">Azure Functions</a>. Even though I don&#8217;t use Azure at all personally (just tried hosting few simple web apps) the topic is interesting showing how easy it can be to build serverless apps or services without setting up any infrastructure.</div>
<div>PS: The photo I&#8217;ve taken was even <a href="https://twitter.com/mangalexandru/status/920980411244740608" target="_blank" rel="noopener">chosen as the photo of the day by Alex</a><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f603.png" alt="😃" class="wp-smiley" style="height: 1em; max-height: 1em;" /> He is active in social media and I definitely recommend to follow this guy.</div>
</div>
<h5><em> Adding history to CRUD (<a href="https://twitter.com/despos" target="_blank" rel="noopener">Dino Esposito</a>)</em></h5>
<p><figure id="attachment_2389" aria-describedby="caption-attachment-2389" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2389" data-permalink="https://www.codejourney.net/net-developer-days-2017/07_dinoaddhisttocrud/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508426480&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;552&quot;,&quot;shutter_speed&quot;:&quot;0.029996322450868&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="07_DinoAddHistToCRUD" data-image-description="" data-image-caption="&lt;p&gt;Dino Esposito on stage&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2389 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/07_DinoAddHistToCRUD.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2389" class="wp-caption-text">Dino Esposito on stage</figcaption></figure></p>
<div>
<div>Dino is a legend. I met him for the first time on the previous edition of the conference last year. When speaking, apart from begin full of humor and telling many jokes, he seems to be so much excited and involved in what he&#8217;s talking about.</div>
<div> </div>
<div>During the presentation Dino showed very engaging mechanism introduced in SQL Server (from version 2016) &#8211; <a href="https://docs.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables" target="_blank" rel="noopener"><strong>temporal tables</strong></a>. Creation of this mechanism was somehow triggered by <a href="http://www.eugdpr.org/" target="_blank" rel="noopener">GDPR</a> regulations introduced last year by the EU parliament. One of the practical consequence of the regulations is that every application processing personal data must <strong>keep full historical track of changes</strong> on this data. Temporal tables give us this possibility &#8220;for free&#8221;. I didn&#8217;t know about this concept and I encourage you to <a href="https://docs.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables" target="_blank" rel="noopener">read about it</a>.</div>
<div>In the end, Dino&#8217;s presentation was very good, slides were great quality and I definitely learnt something new worth knowing.</div>
</div>
<h5><em> Launching patterns for containers &#8211; it&#8217;s more than just scheduling (<a href="https://twitter.com/michelebusta" target="_blank" rel="noopener">Michele Leroux Bustamante</a>)</em></h5>
<p><figure id="attachment_2390" aria-describedby="caption-attachment-2390" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2390" data-permalink="https://www.codejourney.net/net-developer-days-2017/08_michele/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508432358&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;486&quot;,&quot;shutter_speed&quot;:&quot;0.020003676275626&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="08_Michele" data-image-description="" data-image-caption="&lt;p&gt;Michele Bustamante on containers&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2390 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/08_Michele.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2390" class="wp-caption-text">Michele Bustamante on containers</figcaption></figure></p>
<div>Michele&#8217;s presentation was very well organized and clear. I felt she has a huge amount of knowledge and when speaking Michele only says the essentials without unnecessary or not important stuff. We were presented the usage of <a href="https://azure.microsoft.com/en-us/services/container-service/" target="_blank" rel="noopener">Azure Container Service</a> with some demos based on <a href="https://github.com/Jroland/kafka-net" target="_blank" rel="noopener">Kaffka</a> and few different tools.</div>
<div>There were some issues with the demos Michele showed, but this happens to the best even <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<h5><em> Building for the Future without Abandoning the Past (<a href="https://twitter.com/boyofgreen" target="_blank" rel="noopener">Jeff Burtoft</a>)</em></h5>
<p>Jeff is Microsoft&#8217;s employee and you can definitely feel that. Presentation was generally simple and lightweight, but well-told and properly organized. Jeff presented us with some techniques on how to start making our legacy apps/systems better without breaking the previous interfaces and backwards compatibility.</p>
<h5><em><strong> Q&amp;A panel, DevTalk Live and a conference party!</strong></em></h5>
<p>After all 2nd day&#8217;s sessions were finished, we officially started a conference party. During this time we&#8217;ve had some delicious dinner, drunk few craft beers. In the meantime we took a pint and went for a Q&amp;A discussion panel with all the speakers:</p>
<p><figure id="attachment_2391" aria-describedby="caption-attachment-2391" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2391" data-permalink="https://www.codejourney.net/net-developer-days-2017/09_beer_discussionpanel/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508441162&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;246&quot;,&quot;shutter_speed&quot;:&quot;0.020003676275626&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="09_beer_DiscussionPanel" data-image-description="" data-image-caption="&lt;p&gt;#netdd official pint&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2391 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/09_beer_DiscussionPanel.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2391" class="wp-caption-text">#netdd&#8217;s official pint</figcaption></figure></p>
<p>Few very interesting topics were covered during the discussion panel. I think that the most active speakers during the panel were <a href="https://twitter.com/mangalexandru" target="_blank" rel="noopener">Alex</a> and <a href="https://twitter.com/michelebusta" target="_blank" rel="noopener">Michele</a>. <a href="https://twitter.com/despos" target="_blank" rel="noopener">Dino</a> also added quite a few nice insights <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>After the discussion panel there was a 2nd edition of <a href="http://devtalk.pl/" target="_blank" rel="noopener">DevTalk Live</a> hosted by <a href="https://twitter.com/maniserowicz" target="_blank" rel="noopener">Maciej Aniserowicz</a>:</p>
<p><figure id="attachment_2392" aria-describedby="caption-attachment-2392" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2392" data-permalink="https://www.codejourney.net/net-developer-days-2017/10_devtalk/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508445512&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;117&quot;,&quot;shutter_speed&quot;:&quot;0.020003676275626&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="10_DevTalk" data-image-description="&lt;p&gt;DevTalk Live at .NET Developer Days 2017&lt;/p&gt;
" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2392 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/10_DevTalk.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2392" class="wp-caption-text">2nd edition of DevTalk Live</figcaption></figure></p>
<div>Maciej talked with <a href="https://twitter.com/michelebusta" target="_blank" rel="noopener">Michele</a> and <a href="https://twitter.com/gillcleeren" target="_blank" rel="noopener">Gill Cleeren</a>. The main topic of the discussion was <strong>self-development being a programmer</strong>. Speakers discussed whether the programmers should be given time to learn some new technologies at work or they should do it during their free time after working hours. Speakers proposed some nice hybrids of both approaches, but I won&#8217;t make any spoilers, <a href="https://twitter.com/maniserowicz" target="_blank" rel="noopener">Maciej</a> will surely publish the whole conversation so you can listen to it yourself.</div>
<div>What I noticed during the DevTalk Live was that <a href="https://twitter.com/gillcleeren" target="_blank" rel="noopener">Gill Cleeren</a> is a really smart guy, so I decided to see at least one of his Xamarin sessions the next day.</div>
<div> </div>
<h2>Day 3 &#8211; conference 2nd day</h2>
<h5><em> Past, Present &amp; Future of C# Debugging (<a href="https://twitter.com/alon_fliess" target="_blank" rel="noopener">Alon Fliess</a>)</em></h5>
<div>During this presentation Alon showed the <a href="https://oz-code.com/" target="_blank" rel="noopener">OzCode project</a> which is an extension to Visual Studio that can really revolutionize the debugging process, its quality and efficiency. The idea and the tool itself is great &#8211; I really liked it. It helps in debugging by showing the developer a lot more than Visual Studio&#8217;s built-in features. It also enormously improves the efficiency of <a href="https://github.com/oz-code/OzCodeDemo/blob/master/OzCodeDemo/13.LINQ/README.md" target="_blank" rel="noopener">debugging stuff like LINQ expressions</a>.</div>
<div> </div>
<div> </div>
<div>However, <strong>OzCode is a</strong> <strong>paid tool</strong> (free only for active open source contributors whose projects aremeet some pre-defined criteria) and in my opinion presenting such things during a non-sponsored session just <strong>feels wrong</strong>. I had mixed feelings &#8211; I really enjoyed the presentation and the possibilities of OzCode, but on the other hand I knew I will not use it as I don&#8217;t want to pay $175.00 / Yr.</p>
</div>
<div>Nonetheless, if you are interested in trying out OzCode and maybe buying it for yourself or your company, Alon shared with us a link to register for <strong>free 3 months of using OzCode</strong>: <a href="http://tinyurl.com/ozcodedeveloperweek" target="_blank" rel="noopener">http://tinyurl.com/ozcodedeveloperweek</a></div>
<h5><em> Creating a real-world Xamarin application architecture using MVVM (<a href="https://twitter.com/gillcleeren" target="_blank" rel="noopener">Gill Cleeren</a>)</em></h5>
<p><figure id="attachment_2393" aria-describedby="caption-attachment-2393" style="width: 720px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2393" data-permalink="https://www.codejourney.net/net-developer-days-2017/12_gillxamarin/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?fit=4632%2C2608&amp;ssl=1" data-orig-size="4632,2608" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508499600&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;486&quot;,&quot;shutter_speed&quot;:&quot;0.020003676275626&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="12_GillXamarin" data-image-description="" data-image-caption="&lt;p&gt;Gill Cleeren on Xamarin&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?fit=1024%2C577&amp;ssl=1" class="wp-image-2393 size-large" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?resize=720%2C406&#038;ssl=1" alt="" width="720" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?resize=1024%2C577&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/12_GillXamarin.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 720px) 100vw, 720px" /></a><figcaption id="caption-attachment-2393" class="wp-caption-text">Gill Cleeren on MVVM in Xamarin</figcaption></figure></p>
<div>Finally I went to Gill&#8217;s session and that was a <strong>very good decision</strong>. This presentation was <strong>one of the best ones I&#8217;ve seen at .NET Developer Days 2017</strong>. Slides were very good quality and the topic was perfectly interesting for me. As you may know I&#8217;ve been working for a while with Xamarin, however I&#8217;ve never really thought about the architectural aspects of my application on such level. During this session I got to know what is MVVM in terms of Xamarin apps and how <a href="https://github.com/MvvmCross/MvvmCross" target="_blank" rel="noopener">MVVMCross framework</a> can be embedded into the app. I really recommend looking at it if you&#8217;ve also never worked with MVVMCross &#8211; it helps with many things we normally need to do &#8220;manually&#8221; or in a platform-specific way, for instance by adding Data Binding to Xamarin app (which is not present in the core of Xamarin).</div>
<div>Gill prepared a sample app built with MVVMCross &#8211; you can find <a href="https://github.com/GillCleeren/MyTrains" target="_blank" rel="noopener">its source code on his GitHub</a>.</div>
<h2>Organization</h2>
<h5>Registration</h5>
<div>I was privileged by attending the pre-cons workshops on Wednesday, which were held in <a href="http://www.expoxxi.pl/en/" target="_blank" rel="noopener">EXPO XXI</a> &#8211; the same place as the main conference the next day &#8211; and the registration process was held there. It was pretty well organized and took us no more than 10 minutes. The other participants who didn&#8217;t attend the pre-cons told me there were also no issues with the registration directly at the conference on Thursday. If this it true then congrats to organizers for eliminating last year&#8217;s huge queues <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<div>This year we&#8217;ve also been given a really nice gift &#8211; decent laptop backpacks by Natec:</div>
<div>
<figure id="attachment_2394" aria-describedby="caption-attachment-2394" style="width: 234px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2394" data-permalink="https://www.codejourney.net/net-developer-days-2017/14_bag/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?fit=2580%2C3304&amp;ssl=1" data-orig-size="2580,3304" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;2&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;Lenovo K6 NOTE&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1508590374&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;3.59&quot;,&quot;iso&quot;:&quot;694&quot;,&quot;shutter_speed&quot;:&quot;0.020003676275626&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;1&quot;}" data-image-title="14_Bag" data-image-description="" data-image-caption="&lt;p&gt;Laptop backpack &amp;#8211; #netdd gift&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?fit=800%2C1024&amp;ssl=1" class="wp-image-2394 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?resize=234%2C300&#038;ssl=1" alt="" width="234" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?resize=234%2C300&amp;ssl=1 234w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?resize=768%2C984&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?resize=800%2C1024&amp;ssl=1 800w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?resize=720%2C922&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/10/14_Bag.jpg?w=2280&amp;ssl=1 2280w" sizes="auto, (max-width: 234px) 100vw, 234px" /></a><figcaption id="caption-attachment-2394" class="wp-caption-text">Laptop backpack &#8211; #netdd 2017 gift</figcaption></figure></p>
<p>It was a very good idea &#8211; practical and useful gadget.</p>
</div>
<h5>Food</h5>
<p>Food was the same as last year &#8211; very good, huge choice, efficient service. Craft beers served during the conference party on Thursday were also really nice <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h5>Party</h5>
<div>The conference party which I already mentioned was well-organized. We had a lot of places to sit &#8211; so we made a use of it and had a lot of veeeery interesting and inspiring conversations with other participants <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> That&#8217;s a very important part of such events &#8211; <strong>networking</strong> with the others, <strong>getting to know their problems</strong> in their companies, businesses or life. I think this is one of the aspects in our programming community we are missing the most &#8211; meeting others, discussing and exchanging ideas and insights &#8211; not matter which company, country or programming religion you come from.</div>
<div> </div>
<div>The only thing during the party I would improve is to inform the attendees (by loudspeaker for instance) that events like DevTalk Live are starting &#8211; there were maybe around 50-60 people there, whereas it was a great event and some people told me they finally were not there as they didn&#8217;t know when it started.</div>
<h2>Summary</h2>
<div>I really enjoyed .NET Developer Days 2017. In general, compared to the previous edition, there were some organizational things improved like registration and conference gifts. As for the speakers, I have a general feeling that the lecturers were a bit better last year. Sessions held by guys like <a href="https://twitter.com/tedneward" target="_blank" rel="noopener">Ted Neward</a>, <a href="https://twitter.com/jonskeet" target="_blank" rel="noopener">Jon Skeet</a> or <a href="https://twitter.com/maniserowicz" target="_blank" rel="noopener">Maciej Aniserowicz</a> are unforgettable and stay in your mind for a long time.</div>
<div>However, it was great to gain some invaluable knowledge, meet many new people and have a lot of great conversations. Thank you all for organizing and attending the conference. See you next time! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/net-developer-days-2017/">.NET Developer Days 2017</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-developer-days-2017/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2381</post-id>	</item>
		<item>
		<title>Managing Activity state changes using Bundle</title>
		<link>https://www.codejourney.net/managing-activity-state-changes-using-bundle/</link>
					<comments>https://www.codejourney.net/managing-activity-state-changes-using-bundle/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 29 May 2017 21:28:42 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[moneyback]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2281</guid>

					<description><![CDATA[<p>Today we&#8217;re going to see how to manage (keep and restore) state of Activities in Xamarin.Android application in order to keep the app consistent and reactive for configuration/state changes. Why to keep and restore Activity&#8217;s state? As I already described in my post about Android Activities, the OS may react to some &#8220;constant&#8221; state changes&#8230;</p>
<p>The post <a href="https://www.codejourney.net/managing-activity-state-changes-using-bundle/">Managing Activity state changes using Bundle</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today we&#8217;re going to see how to manage (keep and restore) state of <a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener noreferrer">Activities</a> in Xamarin.Android application in order to keep the app consistent and reactive for configuration/state changes.<br />
<span id="more-2281"></span></p>
<h2>Why to keep and restore Activity&#8217;s state?</h2>
<p>As I already described in <a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener noreferrer">my post about Android Activities</a>, the OS may react to some &#8220;constant&#8221; state changes by calling lifecycle methods during Activity&#8217;s life, which may be overridden by the programmer in order to take some additional actions. However, there are some behaviors in Android apps that may change its configuration, after which the state of the Activity (for instance: arrangement or some UI elements or checkboxes&#8217; selections) may be lost if not handled properly.</p>
<p>To give you a real example: in <em>MoneyBack</em> application there is a main screen with two tabs. I noticed that when the second tab is selected:</p>
<p><figure id="attachment_2282" aria-describedby="caption-attachment-2282" style="width: 229px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2282" data-permalink="https://www.codejourney.net/managing-activity-state-changes-using-bundle/moneyback_secondtab/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?fit=1080%2C1920&amp;ssl=1" data-orig-size="1080,1920" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MoneyBack_SecondTab" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?fit=576%2C1024&amp;ssl=1" class="wp-image-2282" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?resize=229%2C406&#038;ssl=1" alt="" width="229" height="406" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 229px) 100vw, 229px" /></a><figcaption id="caption-attachment-2282" class="wp-caption-text"><em>MoneyBack</em> &#8211; 2nd tab selected</figcaption></figure></p>
<p>and the device is rotated:</p>
<p><figure id="attachment_2283" aria-describedby="caption-attachment-2283" style="width: 478px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2283" data-permalink="https://www.codejourney.net/managing-activity-state-changes-using-bundle/moneyback_afterrotatefirsttab/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?fit=1920%2C1080&amp;ssl=1" data-orig-size="1920,1080" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MoneyBack_AfterRotateFirstTab" data-image-description="" data-image-caption="&lt;p&gt;MoneyBack &amp;#8211; 1st tab selected after rotating&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?fit=1024%2C576&amp;ssl=1" class="wp-image-2283" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?resize=478%2C269&#038;ssl=1" alt="" width="478" height="269" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?resize=720%2C405&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?w=1920&amp;ssl=1 1920w" sizes="auto, (max-width: 478px) 100vw, 478px" /></a><figcaption id="caption-attachment-2283" class="wp-caption-text"><em>MoneyBack</em> &#8211; 1st tab selected after rotating</figcaption></figure></p>
<p><strong>first tab becomes selected</strong>. User is losing his input (selection of the 2nd tab).</p>
<p>Screen orientation change is one of the reasons why we should care about saving and restoring Activities&#8217; states.</p>
<h2>Keeping state changes &#8211; OnSaveInstanceState()</h2>
<p>Each Activity allows us to override <span style="color: #ff9900;">OnSaveInstanceState(<span style="color: #ff6600;">Bundle</span> outState)</span> method, which is called when the current Activity is to be killed (e.g. when device&#8217;s screen orientation is changing or the Activity needs to be killed by Android in order to release some resources).</p>
<p><strong>Please don&#8217;t confuse it with Activity Lifecycle Methods</strong> (which I already described <a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener noreferrer">here</a>), like <span style="color: #ff9900;">OnPause()</span> or <span style="color: #ff9900;">OnStop()</span> which are always called by the OS when particular action occurs. <span style="color: #ff9900;">OnSaveInstanceState()</span> method is <strong>generally</strong> called after <span style="color: #ff9900;">OnPause()</span> and before <span style="color: #ff9900;">OnStop()</span>, but <strong>it&#8217;s not always the case</strong>. For instance, it won&#8217;t be called at all when user navigates back from <em>ActivityB</em> to <em>ActivityA</em>, as in this case <em>ActivityB</em> will never be killed. More details can be found in <a href="https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29" target="_blank" rel="noopener noreferrer">official Android documentation</a>.</p>
<p><span style="color: #ff9900;">OnSaveInstanceState()</span> is called with <span style="color: #ff9900;">Bundle</span> parameter provided. It represents a simple key-value dictionary, which is additionally serialized, so it should be used for storing simple values like strings, integers etc. There are other structures and techniques for storing more complex data on state changes events (see the link in &#8220;Summary&#8221; section of this post).</p>
<p>In order to save currently selected tab, we can implement the method as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist48172254" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-onsaveinstancestate-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="OnSaveInstanceState.cs content, created by dsibinski on 08:28PM on May 29, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="OnSaveInstanceState.cs">
<tr>
<td id="file-onsaveinstancestate-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-onsaveinstancestate-cs-LC1" class="blob-code blob-code-inner js-file-line">  protected override void OnSaveInstanceState(Bundle outState)</td>
</tr>
<tr>
<td id="file-onsaveinstancestate-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-onsaveinstancestate-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-onsaveinstancestate-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-onsaveinstancestate-cs-LC3" class="blob-code blob-code-inner js-file-line">      var tabSelectedPosition = this.ActionBar.SelectedNavigationIndex;</td>
</tr>
<tr>
<td id="file-onsaveinstancestate-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-onsaveinstancestate-cs-LC4" class="blob-code blob-code-inner js-file-line">      outState.PutInt(&quot;selectedTabPosition&quot;, tabSelectedPosition);</td>
</tr>
<tr>
<td id="file-onsaveinstancestate-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-onsaveinstancestate-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onsaveinstancestate-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-onsaveinstancestate-cs-LC6" class="blob-code blob-code-inner js-file-line">      base.OnSaveInstanceState(outState);</td>
</tr>
<tr>
<td id="file-onsaveinstancestate-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-onsaveinstancestate-cs-LC7" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/58260052f1fd8a7daffe99d4c63d634c/raw/1b9d19cc7369122ea997616b929899480521dc1e/OnSaveInstanceState.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/58260052f1fd8a7daffe99d4c63d634c#file-onsaveinstancestate-cs" class="Link--inTextBlock"><br />
          OnSaveInstanceState.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Now, each screen orientation change will make this method called and the index of selected tab will be saved into <span style="color: #ff9900;">Bundle</span> <span style="color: #ff9900;">outState</span> dictionary under <em>&#8220;selectedTabPosition&#8221;</em> key.</p>
<h2>Restoring state changes &#8211; OnRestoreInstanceState()</h2>
<p>As soon as the Activity considered backs to life (is being resumed), <span style="color: #ff9900;">OnRestoreInstanceState(<span style="color: #ff6600;">Bundle</span> savedInstanceState)</span> method is called by the OS. <strong>It will only be called if there is a saved instance kept by calling <span style="color: #ff9900;">OnSaveInstanceState()</span> method before</strong>. As you can see, this method also comes with a <span style="color: #ff9900;">Bundle</span> parameter, which is the same key-value serialized dictionary we used for saving the Activity&#8217;s state.</p>
<p>In case of tabs selection restoring, we can implement this method as the following code presents:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist48172407" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-onrestoreinstancestate-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="OnRestoreInstanceState.cs content, created by dsibinski on 08:34PM on May 29, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="OnRestoreInstanceState.cs">
<tr>
<td id="file-onrestoreinstancestate-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-onrestoreinstancestate-cs-LC1" class="blob-code blob-code-inner js-file-line">  protected override void OnRestoreInstanceState(Bundle savedInstanceState)</td>
</tr>
<tr>
<td id="file-onrestoreinstancestate-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-onrestoreinstancestate-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-onrestoreinstancestate-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-onrestoreinstancestate-cs-LC3" class="blob-code blob-code-inner js-file-line">      base.OnRestoreInstanceState(savedInstanceState);</td>
</tr>
<tr>
<td id="file-onrestoreinstancestate-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-onrestoreinstancestate-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onrestoreinstancestate-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-onrestoreinstancestate-cs-LC5" class="blob-code blob-code-inner js-file-line">      var previouslySelectedTabPosition = savedInstanceState.GetInt(&quot;selectedTabPosition&quot;, 0);</td>
</tr>
<tr>
<td id="file-onrestoreinstancestate-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-onrestoreinstancestate-cs-LC6" class="blob-code blob-code-inner js-file-line">      this.ActionBar.SetSelectedNavigationItem(previouslySelectedTabPosition);</td>
</tr>
<tr>
<td id="file-onrestoreinstancestate-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-onrestoreinstancestate-cs-LC7" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/f620e7ae733cda6333cddd9abeced90c/raw/066fc7034dadbcfef47a358ec1c86bbb9a31b7f2/OnRestoreInstanceState.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/f620e7ae733cda6333cddd9abeced90c#file-onrestoreinstancestate-cs" class="Link--inTextBlock"><br />
          OnRestoreInstanceState.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><span style="color: #ff9900;">previouslySelectedTabPosition </span>variable will be initialized with integer value from <span style="color: #ff9900;">Bundle</span> dictionary saved under <em>&#8220;selectedTabPosition&#8221;</em> key, or default value (<em>0</em>) if nothing saved for the key is found.</p>
<p><strong>NOTE</strong>: <span style="color: #ff9900;">Bundle</span> parameter provided in <span style="color: #ff9900;">OnRestoreInstanceState()</span> is exactly the same, as the one available in <span style="color: #ff9900;">OnCreate(<span style="color: #ff6600;">Bundle</span> bundle)</span> method called on Activity&#8217;s creation. We could actually also retrieve our saved value there, but in many cases restoring the state (like selecting previously selected tab) requires some UI elements to be already initialized, which should be handled within <span style="color: #ff9900;">OnCreate()</span> method before. Because of that, I&#8217;d rather suggest to restore Activity&#8217;s state using <span style="color: #ff9900;">OnRestoreInstanceState()</span> as a general rule (of course there may be some exceptional cases <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ). <span style="color: #ff9900;">OnRestoreInstanceState()</span> will always be called <strong>after</strong> <span style="color: #ff9900;">OnCreate()</span>.</p>
<p>Moreover, if we wanted to use <span style="color: #ff9900;">Bundle</span> parameter in <span style="color: #ff9900;">OnCreate()</span> method, we&#8217;d need to check each time if <span style="color: #ff9900;">bundle</span> is not NULL (as we don&#8217;t know whether <span style="color: #ff9900;">OnSaveInstanceState()</span> had been called before).</p>
<p>As a result, the same tab as previously is selected even after rotating the device on <em>MoneyBack</em>&#8216;s <span style="color: #ff9900;">MainActivity</span>:</p>
<p><figure id="attachment_2287" aria-describedby="caption-attachment-2287" style="width: 826px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2287" data-permalink="https://www.codejourney.net/managing-activity-state-changes-using-bundle/moneyback_rotate2-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?fit=4052%2C1968&amp;ssl=1" data-orig-size="4052,1968" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MoneyBack_rotate2" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?fit=1024%2C497&amp;ssl=1" class="wp-image-2287" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?resize=826%2C402&#038;ssl=1" alt="" width="826" height="402" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?resize=300%2C146&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?resize=768%2C373&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?resize=1024%2C497&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?resize=720%2C350&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 826px) 100vw, 826px" /></a><figcaption id="caption-attachment-2287" class="wp-caption-text"><em>MoneyBack</em> &#8211; keeping tab selected when rotating</figcaption></figure></p>
<h2>&#8220;Automatic&#8221; state changes handled by Android OS</h2>
<p>Maybe you noticed in your Android application, that not every UI element needs to be handled &#8220;manually&#8221; by implementing the above-mentioned methods in order to save its state. Android performs some kind of &#8220;automatic&#8221; saving and restoration of basic UI elements&#8217; states.</p>
<p>The rule here is that as long as UI element (like <span style="color: #ff9900;">TextView</span> or <span style="color: #ff9900;">Button</span>) has its <span style="color: #ff9900;">android:id</span> set in <em>.axml</em> layout file, OS will automatically manage those elements&#8217; states (e.g. text entered into <span style="color: #ff9900;">EditText</span>).</p>
<p>For example, for <span style="color: #ff9900;">EditText</span> declared like that:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist48172903" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-edittext-axml" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-xml  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="EditText.axml content, created by dsibinski on 08:51PM on May 29, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="EditText.axml">
<tr>
<td id="file-edittext-axml-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-edittext-axml-LC1" class="blob-code blob-code-inner js-file-line">  &lt;EditText</td>
</tr>
<tr>
<td id="file-edittext-axml-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-edittext-axml-LC2" class="blob-code blob-code-inner js-file-line">  android:layout_width=&quot;match_parent&quot;</td>
</tr>
<tr>
<td id="file-edittext-axml-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-edittext-axml-LC3" class="blob-code blob-code-inner js-file-line">  android:layout_height=&quot;wrap_content&quot;</td>
</tr>
<tr>
<td id="file-edittext-axml-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-edittext-axml-LC4" class="blob-code blob-code-inner js-file-line">  android:id=&quot;@+id/inputEventName&quot;</td>
</tr>
<tr>
<td id="file-edittext-axml-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-edittext-axml-LC5" class="blob-code blob-code-inner js-file-line">  android:fadingEdge=&quot;none&quot; /&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/0b3920ba34d87ac7b8d70bab199dd430/raw/c41dc4d096994c0be50c064a2f3331c7e7a710d3/EditText.axml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/0b3920ba34d87ac7b8d70bab199dd430#file-edittext-axml" class="Link--inTextBlock"><br />
          EditText.axml<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>its properties (especially its <strong>Text</strong> property) will be automatically saved and restored on screen orientation changes.</p>
<h2>Summary</h2>
<p>We&#8217;ve seen how to handle Android Activities&#8217; state changes caused by configuration modification (e.g. screen orientation change, Activity being killed by the OS in order to free some resources etc.) by implementing <span style="color: #ff9900;">OnSaveInstanceState()</span> and <span style="color: #ff9900;">OnRestoreInstanceState()</span>, where we added and retrieved key-value data to/from <span style="color: #ff9900;">Bundle</span> serialized dictionary. We just need to remember that those methods are not always called (e.g. when navigating between Activities using &#8220;back&#8221; button), so these should be used only for certain kind of state changes.</p>
<p>We&#8217;ve also seen that UI controls with their <span style="color: #ff9900;">android:id</span> defined in layout files have their states <em>resistant</em> for configuration changes (handled automatically by Android OS).</p>
<p><span style="color: #ff9900;">Bundle</span> dictionary is serialized for better performance and memory utilization, so only simple-typed values should be stored in it (like strings or integers). In order to store more complex data, Android provides different possibilities of managing it (e.g. using <a href="https://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance()" target="_blank" rel="noopener noreferrer">OnRetainNonConfigurationInstance</a>).</p>
<p>The post <a href="https://www.codejourney.net/managing-activity-state-changes-using-bundle/">Managing Activity state changes using Bundle</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/managing-activity-state-changes-using-bundle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2281</post-id>	</item>
		<item>
		<title>Date selection using DatePickerDialog in Xamarin.Android</title>
		<link>https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/</link>
					<comments>https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 27 May 2017 13:19:47 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[moneyback]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2266</guid>

					<description><![CDATA[<p>In this post, we&#8217;re going to see how to provide a nice Android UI control for selecting the date using DatePickerDialog. The dialog looks as follows: It may be opened e.g. when clicking on a button in the app, as I used it in MoneyBack. Creating DatePickerFragment First of all, we will implement the dialog to be displayed&#8230;</p>
<p>The post <a href="https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/">Date selection using DatePickerDialog in Xamarin.Android</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this post, we&#8217;re going to see how to provide a nice Android UI control for selecting the date using <span style="color: #ff9900;">DatePickerDialog</span>.<br />
<span id="more-2266"></span></p>
<p>The dialog looks as follows:</p>
<p><figure id="attachment_2267" aria-describedby="caption-attachment-2267" style="width: 238px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2267" data-permalink="https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/event_datepicker/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?fit=1080%2C1920&amp;ssl=1" data-orig-size="1080,1920" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Event_DatePicker" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?fit=576%2C1024&amp;ssl=1" class="wp-image-2267 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?resize=238%2C423&#038;ssl=1" alt="" width="238" height="423" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 238px) 100vw, 238px" /></a><figcaption id="caption-attachment-2267" class="wp-caption-text">DatePickerDialog</figcaption></figure></p>
<p>It may be opened e.g. when clicking on a button in the app, as I used it in <em>MoneyBack</em>.</p>
<h2>Creating DatePickerFragment</h2>
<p>First of all, we will implement the dialog to be displayed within <span style="color: #ff6600;">DialogFragment.</span> Doing that our dialog will be able to be displayed as independent piece of UI on the top of any Activity.</p>
<p>The second requirement is to implement <span style="color: #ff6600;">IOnDateSetListener</span> interface (coming from Java/Android), which provides a callback on date selection action done by the user.</p>
<p>The <span style="color: #ff6600;">DatePickerFragment</span> meeting those two requirements may look as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist48103396" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-datepickerfragment-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="DatePickerFragment.cs content, created by dsibinski on 12:35PM on May 27, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="DatePickerFragment.cs">
<tr>
<td id="file-datepickerfragment-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-datepickerfragment-cs-LC1" class="blob-code blob-code-inner js-file-line">  public class DatePickerFragment : DialogFragment, DatePickerDialog.IOnDateSetListener</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-datepickerfragment-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-datepickerfragment-cs-LC3" class="blob-code blob-code-inner js-file-line">      public static readonly string TAG = &quot;X:&quot; + typeof(DatePickerFragment).Name.ToUpper();</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-datepickerfragment-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-datepickerfragment-cs-LC5" class="blob-code blob-code-inner js-file-line">      Action&lt;DateTime&gt; _dateSelectedHandler = delegate { };</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-datepickerfragment-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-datepickerfragment-cs-LC7" class="blob-code blob-code-inner js-file-line">      public DatePickerFragment(Action&lt;DateTime&gt; onDateSelected)</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-datepickerfragment-cs-LC8" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-datepickerfragment-cs-LC9" class="blob-code blob-code-inner js-file-line">          _dateSelectedHandler = onDateSelected;</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-datepickerfragment-cs-LC10" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-datepickerfragment-cs-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-datepickerfragment-cs-LC12" class="blob-code blob-code-inner js-file-line">      public override Dialog OnCreateDialog(Bundle savedInstanceState)</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-datepickerfragment-cs-LC13" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-datepickerfragment-cs-LC14" class="blob-code blob-code-inner js-file-line">          DateTime now = DateTime.Now;</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-datepickerfragment-cs-LC15" class="blob-code blob-code-inner js-file-line">          return new DatePickerDialog(Activity, </td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-datepickerfragment-cs-LC16" class="blob-code blob-code-inner js-file-line">              this,</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-datepickerfragment-cs-LC17" class="blob-code blob-code-inner js-file-line">              now.Year,</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-datepickerfragment-cs-LC18" class="blob-code blob-code-inner js-file-line">              now.Month,</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-datepickerfragment-cs-LC19" class="blob-code blob-code-inner js-file-line">              now.Day);</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-datepickerfragment-cs-LC20" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-datepickerfragment-cs-LC21" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-datepickerfragment-cs-LC22" class="blob-code blob-code-inner js-file-line">      public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-datepickerfragment-cs-LC23" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-datepickerfragment-cs-LC24" class="blob-code blob-code-inner js-file-line">          DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-datepickerfragment-cs-LC25" class="blob-code blob-code-inner js-file-line">          _dateSelectedHandler(selectedDate);</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-datepickerfragment-cs-LC26" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-datepickerfragment-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-datepickerfragment-cs-LC27" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/6bddb5f760a83b1d190d7d20362f1546/raw/eb5d54ac22e31860c2925eaa58ec078d545d43d2/DatePickerFragment.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/6bddb5f760a83b1d190d7d20362f1546#file-datepickerfragment-cs" class="Link--inTextBlock"><br />
          DatePickerFragment.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>There are few crucial parts in above-listed class:</p>
<ul>
<li>Line 1: as said before, the class derives from <span style="color: #ff6600;">DialogFragment</span> and implements <span style="color: #ff6600;">IOnDateSetListener</span> interface</li>
<li>Line 3: here we have <span style="color: #ff6600;">public static readonly string TAG</span> variable defined &#8211; it is used as a unique identifier of the <span style="color: #ff6600;">Fragment</span>; in some cases, <span style="color: #ff6600;">Fragments</span> can be displayed without any UI &#8211; in such case the only possibility to identify and get the <span style="color: #ff6600;">Fragment</span> is by using <a href="https://developer.android.com/reference/android/app/FragmentManager.html#findFragmentByTag(java.lang.String)" target="_blank" rel="noopener noreferrer">findFragmentByTag()</a> method</li>
<li>Lines 5-10: define <span style="color: #ff6600;">_dateSelectedHandler</span> delegate which may be provided to the constructor of our <span style="color: #ff6600;">DatePickerFragment</span> with the method to be called-back when user selects a date</li>
<li>Lines 12-20: inheriting from <span style="color: #ff6600;">DialogFragment</span> allows us to override its <a href="https://developer.android.com/reference/android/app/DialogFragment.html#Lifecycle" target="_blank" rel="noopener noreferrer">lifecycle methods</a> &#8211; one of them is <span style="color: #ff6600;">Dialog <span style="color: #993300;">OnCreateDialog</span>(Bundle <span style="color: #993300;">savedInstanceState</span>)</span>, in which we actually create the <span style="color: #ff6600;">Dialog</span>-inheriting class &#8211; in our case &#8211; <span style="color: #ff6600;">DatePickerDialog</span> &#8211; with initially selected date (set to current date in the provided example)</li>
<li>Lines 22-26: implementing <span style="color: #ff9900;">IOnDateSetListener </span>interface requires to implement <span style="color: #ff9900;">OnDateSet</span> method, which is called when the user selects the date and clicks &#8220;OK&#8221; button;<b><br />
NOTE</b>: one of this method&#8217;s arguments is <span style="color: #ff9900;">monthOfYear</span> integer value, which contains month number expressed as values 0-11 (NOT 1-12) for compatibility with <a href="https://developer.android.com/reference/java/util/Calendar.html#MONTH" target="_blank" rel="noopener noreferrer">java.util.Calendar.MONTH</a></li>
</ul>
<h2>Using DatePickerFragment</h2>
<p>In <em>MoneyBack</em> application I&#8217;ve used <span style="color: #ff9900;">DatePickerFragment</span> on creating/modifying an event, when user needs to select its date:</p>
<p><figure id="attachment_2275" aria-describedby="caption-attachment-2275" style="width: 223px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2275" data-permalink="https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/event_dateselection/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?fit=1080%2C1920&amp;ssl=1" data-orig-size="1080,1920" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Event_DateSelection" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?fit=576%2C1024&amp;ssl=1" class="wp-image-2275" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?resize=223%2C396&#038;ssl=1" alt="" width="223" height="396" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 223px) 100vw, 223px" /></a><figcaption id="caption-attachment-2275" class="wp-caption-text"><em>MoneyBack</em> &#8211; event&#8217;s date selection</figcaption></figure></p>
<p>As soon as the button is clicked, the following code executes:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist48103872" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-eventdetailsactivity_dateclick-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="EventDetailsActivity_DateClick.cs content, created by dsibinski on 12:57PM on May 27, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="EventDetailsActivity_DateClick.cs">
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC1" class="blob-code blob-code-inner js-file-line">  private void _btnSelectDate_Click(object sender, EventArgs e)</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC3" class="blob-code blob-code-inner js-file-line">      new DatePickerFragment(delegate(DateTime time)</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC4" class="blob-code blob-code-inner js-file-line">          {</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC5" class="blob-code blob-code-inner js-file-line">              _selectedDate = time;</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC6" class="blob-code blob-code-inner js-file-line">              _btnSelectDate.Text = _selectedDate.ToLongDateString();</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC7" class="blob-code blob-code-inner js-file-line">          })</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC8" class="blob-code blob-code-inner js-file-line">          .Show(FragmentManager, DatePickerFragment.TAG);</td>
</tr>
<tr>
<td id="file-eventdetailsactivity_dateclick-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-eventdetailsactivity_dateclick-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/930a05f6a51752d773651941b1dd5135/raw/4ef6b702c3c5ee9580a66ee6aef6310772856ad7/EventDetailsActivity_DateClick.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/930a05f6a51752d773651941b1dd5135#file-eventdetailsactivity_dateclick-cs" class="Link--inTextBlock"><br />
          EventDetailsActivity_DateClick.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>As you can see, to <span style="color: #ff9900;">DatePickerFragment</span>&#8216;s constructor I&#8217;m providing the delegate with a method to be called when the date is selected by the user (setting <span style="color: #ff9900;">_selectedDate</span> property with selected <span style="color: #ff9900;">time</span> and putting the date in short format as button&#8217;s <span style="color: #ff9900;">Text</span>).</p>
<p>In order to display a dialog, <a href="https://developer.android.com/reference/android/app/DialogFragment.html#show(android.app.FragmentManager, java.lang.String)" target="_blank" rel="noopener noreferrer">Show</a> method is called, taking current <span style="color: #ff9900;">FragmentManager</span> and already mentioned per-Fragment-unique <span style="color: #ff9900;">tag string</span>, defined statically in <span style="color: #ff9900;">DatePickerFragment</span> class.</p>
<h2>Summary</h2>
<p>Today&#8217;s short post presented how to easily create a <span style="color: #ff9900;">DialogFragment</span> showing <span style="color: #ff9900;">DatePickerDialog</span> for date selection, which allows to provide any method to be called-back when the date is selected by the user.</p>
<p>I hope you&#8217;ll find it useful <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/">Date selection using DatePickerDialog in Xamarin.Android</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/date-selection-using-datepickerdialog-in-xamarin-android/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2266</post-id>	</item>
		<item>
		<title>SQLite-Net Extensions – one-to-many relationships</title>
		<link>https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/</link>
					<comments>https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 22 May 2017 22:01:46 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[sqlite-net-extensions]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2251</guid>

					<description><![CDATA[<p>In the 3rd post from SQLite-Net Extensions series we are covering the last type of relationship &#8211; one-to-many (and the opposite &#8211; many-to-one). One-to-many, many-to-one One-to-many relationships are used in general for parent-children or whole-elements relations. Classic examples are: bus and passengers, document and elements etc. One-to-many relationship means that the one-end entity knows about its&#8230;</p>
<p>The post <a href="https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/">SQLite-Net Extensions – one-to-many relationships</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the 3rd post from <a href="https://www.codejourney.net/tag/sqlite-net-extensions/" target="_blank" rel="noopener noreferrer">SQLite-Net Extensions series</a> we are covering the last type of relationship &#8211; <em>one-to-many</em> (and the opposite &#8211; <em>many-to-one</em>).<br />
<span id="more-2251"></span></p>
<h2>One-to-many, many-to-one</h2>
<p><strong>One-to-many</strong> relationships are used in general for <em>parent-children</em> or <em>whole-elements</em> relations. Classic examples are: bus and passengers, document and elements etc.</p>
<p>One-to-many relationship means that the <em>one-end</em> entity knows about its children and <em>many-end</em> entity has a reference (foreign key) to its parent (but not necessarily <span style="text-decoration: underline;">knows</span> about it).</p>
<p>On the other hand, the opposite relationship to one-to-many is <strong>many-to-one</strong>. In that case, <em>many-end</em> entity has a reference to its parent and <span style="text-decoration: underline;">knows </span>about it, but the <em>one-end</em> entity doesn&#8217;t necessarily <span style="text-decoration: underline;">know</span> about its children (at least not directly).</p>
<p>I used a verb <span style="text-decoration: underline;">to know</span> several times &#8211; so it&#8217;s time to explain it 🙂 By &#8220;knowing&#8221; about the other end of a relationship I understand <span style="text-decoration: underline;">having a reference to it</span>. It means that, for instance, in many-to-one relationship, the one-end of it doesn&#8217;t have a reference to its children.</p>
<p>However in most cases what we&#8217;d like to have is a <strong>hybrid of one-to-many and many-to-one relationships</strong>. I will call it <strong>one-to-many with inversion</strong>. We want both parent to know about its children, and each children to know about its parent.</p>
<p>In this post we&#8217;ll cover one-to-many with no reversion and one-to-many with reversion, as it also includes many-to-one relationship so you can have a comprehensive overview. We are going to see it on the example of <strong>Employee</strong> and <strong>Duty*</strong> entities. Each employee has a list of his duties, whilst each single duty is assigned to only one employee.</p>
<p><span style="font-size: 10pt;">* &#8220;Task&#8221; would probably be a better name, but I didn&#8217;t want to make it confused with <a href="https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx" target="_blank" rel="noopener noreferrer">.NET Tasks</a> 🙂</span></p>
<h2>One-to-many with no inversion</h2>
<p>Firstly, let&#8217;s model this kind of relationship:</p>
<p><figure id="attachment_2252" aria-describedby="caption-attachment-2252" style="width: 485px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2252" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/1tm_noinv_uml/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?fit=783%2C149&amp;ssl=1" data-orig-size="783,149" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;Dawid Sibi\u0144ski&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1495493793&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="1tm_noInv_UML" data-image-description="" data-image-caption="&lt;p&gt;One-to-many with no inversion &amp;#8211; class diagram&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?fit=783%2C149&amp;ssl=1" class="wp-image-2252" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?resize=485%2C92&#038;ssl=1" alt="" width="485" height="92" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?resize=300%2C57&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?resize=768%2C146&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?resize=720%2C137&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?w=783&amp;ssl=1 783w" sizes="auto, (max-width: 485px) 100vw, 485px" /></a><figcaption id="caption-attachment-2252" class="wp-caption-text">One-to-many with no inversion &#8211; class diagram</figcaption></figure></p>
<p>Now we can transform it into C# classes:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47944669" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-employee-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Employee.cs content, created by dsibinski on 08:58PM on May 22, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Employee.cs">
<tr>
<td id="file-employee-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-employee-cs-LC1" class="blob-code blob-code-inner js-file-line">    [Table(&quot;Employees&quot;)]</td>
</tr>
<tr>
<td id="file-employee-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-employee-cs-LC2" class="blob-code blob-code-inner js-file-line">    public class Employee</td>
</tr>
<tr>
<td id="file-employee-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-employee-cs-LC3" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-employee-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-employee-cs-LC4" class="blob-code blob-code-inner js-file-line">        [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-employee-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-employee-cs-LC5" class="blob-code blob-code-inner js-file-line">        public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-employee-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-employee-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employee-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-employee-cs-LC7" class="blob-code blob-code-inner js-file-line">        public string Name { get; set; }</td>
</tr>
<tr>
<td id="file-employee-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-employee-cs-LC8" class="blob-code blob-code-inner js-file-line">        public string LastName { get; set; }</td>
</tr>
<tr>
<td id="file-employee-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-employee-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employee-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-employee-cs-LC10" class="blob-code blob-code-inner js-file-line">        [OneToMany]</td>
</tr>
<tr>
<td id="file-employee-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-employee-cs-LC11" class="blob-code blob-code-inner js-file-line">        public List&lt;Duty&gt; Duties { get; set; }</td>
</tr>
<tr>
<td id="file-employee-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-employee-cs-LC12" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7a4bba5b4769a57e286b951d7d830965/raw/5eea39ad5f5ed9597cad5cd3c3677da964b7e42f/Employee.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7a4bba5b4769a57e286b951d7d830965#file-employee-cs" class="Link--inTextBlock"><br />
          Employee.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In the <span style="color: #ff6600;">Employee</span> class (parent, one-end of the relationship) we define the collection of children, decorated with <span style="color: #ff6600;">OneToManyAttribute</span>. Collections types supported as for the time of writing this post by SQLite-Net Extensions are <a href="https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx" target="_blank" rel="noopener noreferrer">List</a> and <a href="https://msdn.microsoft.com/en-us/library/system.array(v=vs.110).aspx" target="_blank" rel="noopener noreferrer">Array</a> and can be used as you prefer.</p>
<p>Let&#8217;s now see how the child entity (<span style="color: #ff6600;">Duty</span>) looks like:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47944678" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-duty-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Duty.cs content, created by dsibinski on 08:59PM on May 22, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Duty.cs">
<tr>
<td id="file-duty-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-duty-cs-LC1" class="blob-code blob-code-inner js-file-line">    [Table(&quot;Duties&quot;)]</td>
</tr>
<tr>
<td id="file-duty-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-duty-cs-LC2" class="blob-code blob-code-inner js-file-line">    public class Duty</td>
</tr>
<tr>
<td id="file-duty-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-duty-cs-LC3" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-duty-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-duty-cs-LC4" class="blob-code blob-code-inner js-file-line">        [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-duty-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-duty-cs-LC5" class="blob-code blob-code-inner js-file-line">        public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-duty-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-duty-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-duty-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-duty-cs-LC7" class="blob-code blob-code-inner js-file-line">        public string Description { get; set; }</td>
</tr>
<tr>
<td id="file-duty-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-duty-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-duty-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-duty-cs-LC9" class="blob-code blob-code-inner js-file-line">        public DateTime Deadline { get; set; }</td>
</tr>
<tr>
<td id="file-duty-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-duty-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-duty-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-duty-cs-LC11" class="blob-code blob-code-inner js-file-line">        [ForeignKey(typeof(Employee))]</td>
</tr>
<tr>
<td id="file-duty-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-duty-cs-LC12" class="blob-code blob-code-inner js-file-line">        public int EmployeeId { get; set; }</td>
</tr>
<tr>
<td id="file-duty-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-duty-cs-LC13" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/194a755eb249ea9b4b2a2957c8a5bdbd/raw/b482ad831f693d7d06db28e89c462c3fe3f055d9/Duty.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/194a755eb249ea9b4b2a2957c8a5bdbd#file-duty-cs" class="Link--inTextBlock"><br />
          Duty.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In the <span style="color: #ff6600;">Duty</span> class (child, many-end of the relationship) we need to have a foreign key to parent entity defined. For that purpose, we create a property representing it (<span style="color: #ff6600;">EmployeeId</span>), decorating it with <span style="color: #ff6600;">ForeignKeyAttribute</span>, additionally specifying the type of parent referenced (<span style="color: #ff6600;">Employee</span>).</p>
<p>That&#8217;s it. We can already use it in our code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47944855" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-employeeduty_noinv-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="EmployeeDuty_noInv.cs content, created by dsibinski on 09:05PM on May 22, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="EmployeeDuty_noInv.cs">
<tr>
<td id="file-employeeduty_noinv-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-employeeduty_noinv-cs-LC1" class="blob-code blob-code-inner js-file-line">  var db = new SQLiteConnection(new SQLitePlatformAndroid(), Constants.DbFilePath);</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-employeeduty_noinv-cs-LC2" class="blob-code blob-code-inner js-file-line">  db.CreateTable&lt;Employee&gt;();</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-employeeduty_noinv-cs-LC3" class="blob-code blob-code-inner js-file-line">  db.CreateTable&lt;Duty&gt;();</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-employeeduty_noinv-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-employeeduty_noinv-cs-LC5" class="blob-code blob-code-inner js-file-line">  var employee = new Employee</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-employeeduty_noinv-cs-LC6" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-employeeduty_noinv-cs-LC7" class="blob-code blob-code-inner js-file-line">      Name = &quot;Andrew&quot;,</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-employeeduty_noinv-cs-LC8" class="blob-code blob-code-inner js-file-line">      LastName = &quot;Programmer&quot;</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-employeeduty_noinv-cs-LC9" class="blob-code blob-code-inner js-file-line">  };</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-employeeduty_noinv-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-employeeduty_noinv-cs-LC11" class="blob-code blob-code-inner js-file-line">  var duty1 = new Duty()</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-employeeduty_noinv-cs-LC12" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-employeeduty_noinv-cs-LC13" class="blob-code blob-code-inner js-file-line">      Description = &quot;Project A Management&quot;,</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-employeeduty_noinv-cs-LC14" class="blob-code blob-code-inner js-file-line">      Deadline = new DateTime(2017, 10, 31)</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-employeeduty_noinv-cs-LC15" class="blob-code blob-code-inner js-file-line">  };</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-employeeduty_noinv-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-employeeduty_noinv-cs-LC17" class="blob-code blob-code-inner js-file-line">  var duty2 = new Duty()</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-employeeduty_noinv-cs-LC18" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-employeeduty_noinv-cs-LC19" class="blob-code blob-code-inner js-file-line">      Description = &quot;Reporting work time&quot;,</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-employeeduty_noinv-cs-LC20" class="blob-code blob-code-inner js-file-line">      Deadline = new DateTime(2022, 12, 31)</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-employeeduty_noinv-cs-LC21" class="blob-code blob-code-inner js-file-line">  };</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-employeeduty_noinv-cs-LC22" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-employeeduty_noinv-cs-LC23" class="blob-code blob-code-inner js-file-line">  db.Insert(employee);</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-employeeduty_noinv-cs-LC24" class="blob-code blob-code-inner js-file-line">  db.Insert(duty1);</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-employeeduty_noinv-cs-LC25" class="blob-code blob-code-inner js-file-line">  db.Insert(duty2);</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-employeeduty_noinv-cs-LC26" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-employeeduty_noinv-cs-LC27" class="blob-code blob-code-inner js-file-line">  employee.Duties = new List&lt;Duty&gt; {duty1, duty2};</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-employeeduty_noinv-cs-LC28" class="blob-code blob-code-inner js-file-line">  db.UpdateWithChildren(employee);</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
<td id="file-employeeduty_noinv-cs-LC29" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employeeduty_noinv-cs-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
<td id="file-employeeduty_noinv-cs-LC30" class="blob-code blob-code-inner js-file-line">  var employeeStored = db.GetWithChildren&lt;Employee&gt;(employee.Id);</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/75df037ed90ffab99e5bb313241e8e3c/raw/b24fce0392c8be8078423f1d4c472ced73eef96a/EmployeeDuty_noInv.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/75df037ed90ffab99e5bb313241e8e3c#file-employeeduty_noinv-cs" class="Link--inTextBlock"><br />
          EmployeeDuty_noInv.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>No rocket-science here. What&#8217;s interesting for us it how <span style="color: #ff6600;">employeeStored</span> looks in the end:</p>
<p><figure id="attachment_2260" aria-describedby="caption-attachment-2260" style="width: 468px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2260" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/1tm_noinv_debug-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?fit=478%2C171&amp;ssl=1" data-orig-size="478,171" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="1tM_noInv_debug" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?fit=478%2C171&amp;ssl=1" class="wp-image-2260" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?resize=468%2C167&#038;ssl=1" alt="" width="468" height="167" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?resize=300%2C107&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?w=478&amp;ssl=1 478w" sizes="auto, (max-width: 468px) 100vw, 468px" /></a><figcaption id="caption-attachment-2260" class="wp-caption-text">One-to-many with no inversion</figcaption></figure></p>
<p>As you can see, <span style="color: #ff6600;">GetWithChildren</span> method returned object of type <span style="color: #ff6600;">Employee</span> with its <span style="color: #ff6600;">Duties</span> collection properly retrieved (containing two duties assigned to the employee before). Moreover, each children has its foreign key (<span style="color: #ff6600;">EmployeeId</span>) automatically retrieved from the DB &#8211; there is no overhead here, this is simply foreign key field stored in the same SQLite database table (<em>Duties</em>).</p>
<h2>One-to-many with inversion (one-to-many + many-to-one)</h2>
<p>As previously, let&#8217;s first see how the class diagram changes after adding inversion:</p>
<p><figure id="attachment_2259" aria-describedby="caption-attachment-2259" style="width: 504px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2259" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/1tm_withinv_uml/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?fit=790%2C156&amp;ssl=1" data-orig-size="790,156" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;Dawid Sibi\u0144ski&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1495493850&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="1tm_withInv_UML" data-image-description="" data-image-caption="&lt;p&gt;One-to-many with inversion&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?fit=790%2C156&amp;ssl=1" class="wp-image-2259" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?resize=504%2C99&#038;ssl=1" alt="" width="504" height="99" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?resize=300%2C59&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?resize=768%2C152&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?resize=720%2C142&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?w=790&amp;ssl=1 790w" sizes="auto, (max-width: 504px) 100vw, 504px" /></a><figcaption id="caption-attachment-2259" class="wp-caption-text">One-to-many with inversion &#8211; class diagram</figcaption></figure></p>
<p>What changed is that now each <span style="color: #ff6600;">Duty</span> has a property of type <span style="color: #ff6600;">Employee</span>.</p>
<p>To realize the above class diagram and make each children (each <span style="color: #ff6600;">Duty</span> in our case) knowing about its parent (having a reference to responsible <span style="color: #ff6600;">Employee</span>), the only thing we need to do is to add the following property to <span style="color: #ff6600;">Duty</span> model class:</p>
<pre><pre class="brush: csharp; title: ; notranslate">&#x5B;ManyToOne]
public Employee Employee { get; set; }</pre>
<p>so the model class finally looks as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47945603" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-employee_withinv-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Employee_withInv.cs content, created by dsibinski on 09:34PM on May 22, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Employee_withInv.cs">
<tr>
<td id="file-employee_withinv-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-employee_withinv-cs-LC1" class="blob-code blob-code-inner js-file-line">  [Table(&quot;Duties&quot;)]</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-employee_withinv-cs-LC2" class="blob-code blob-code-inner js-file-line">  public class Duty</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-employee_withinv-cs-LC3" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-employee_withinv-cs-LC4" class="blob-code blob-code-inner js-file-line">      [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-employee_withinv-cs-LC5" class="blob-code blob-code-inner js-file-line">      public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-employee_withinv-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-employee_withinv-cs-LC7" class="blob-code blob-code-inner js-file-line">      public string Description { get; set; }</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-employee_withinv-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-employee_withinv-cs-LC9" class="blob-code blob-code-inner js-file-line">      public DateTime Deadline { get; set; }</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-employee_withinv-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-employee_withinv-cs-LC11" class="blob-code blob-code-inner js-file-line">      [ForeignKey(typeof(Employee))]</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-employee_withinv-cs-LC12" class="blob-code blob-code-inner js-file-line">      public int EmployeeId { get; set; }</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-employee_withinv-cs-LC13" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-employee_withinv-cs-LC14" class="blob-code blob-code-inner js-file-line">      [ManyToOne]</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-employee_withinv-cs-LC15" class="blob-code blob-code-inner js-file-line">      public Employee Employee { get; set; }</td>
</tr>
<tr>
<td id="file-employee_withinv-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-employee_withinv-cs-LC16" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/270d672a47715a6f0e76ce4747048b3d/raw/fdc1e5a1af839cc859d2b706018f45af64335501/Employee_withInv.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/270d672a47715a6f0e76ce4747048b3d#file-employee_withinv-cs" class="Link--inTextBlock"><br />
          Employee_withInv.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>As you can see, we have just created many-to-one relationship by using <span style="color: #ff6600;">ManyToOneAttribute</span>. So currently we have the hybrid of both types of relationships within out two models.</p>
<p>The usage in our code doesn&#8217;t need to be changed at all. Now, <span style="color: #ff6600;">employeeStored</span> entity after being initialized by the same <span style="color: #ff6600;">GetWithChildren</span> method as previously, for each <span style="color: #ff6600;">Duty</span> in addition to <span style="color: #ff6600;">EmployeeId</span> field also contains <span style="color: #ff6600;">Employee</span> property properly retrieved by SQLite-Net Extensions:</p>
<p><figure id="attachment_2261" aria-describedby="caption-attachment-2261" style="width: 469px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2261" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/1tm_withinv_debug/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?fit=475%2C160&amp;ssl=1" data-orig-size="475,160" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="1tM_withInv_debug" data-image-description="" data-image-caption="&lt;p&gt;One-to-many with inversion&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?fit=475%2C160&amp;ssl=1" class="wp-image-2261" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?resize=469%2C158&#038;ssl=1" alt="" width="469" height="158" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?resize=300%2C101&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?w=475&amp;ssl=1 475w" sizes="auto, (max-width: 469px) 100vw, 469px" /></a><figcaption id="caption-attachment-2261" class="wp-caption-text">One-to-many with inversion</figcaption></figure></p>
<p>Again, there is no db overhead here, because when retrieving <span style="color: #ff6600;">Employee</span> entity from the database we already have it, so the operation of initializing the <span style="color: #ff6600;">Employee</span> entity in each <span style="color: #ff6600;">Duty</span> contained within <span style="color: #ff6600;">Duties</span> collection doesn&#8217;t require any more database querying.</p>
<h2>Summary</h2>
<p>Today we&#8217;ve seen how to model and use one-to-many (with and without inversion) relationships in SQLite database with the usage of SQLite-Net Extensions. The automatic initialization of one-end or many-end entities by the ORM is extremely helpful when dealing with such kind of objects in our app. The amount of code to be written is also minimal.</p>
<p>We&#8217;ve covered one-to-many and a hybrid of one-to-many + many-to-one relationships, but of course you can also define just many-to-one relationship &#8211; the models would then look <a href="https://gist.github.com/dsibinski/9d4f47a85d4944fb55a888aff57a84a3" target="_blank" rel="noopener noreferrer">as in this Gist</a>. For me, it makes very limited sense, but maybe can be useful in some specific situations.</p>
<p>I invite you to read <a href="https://www.codejourney.net/tag/sqlite-net-extensions/" target="_blank" rel="noopener noreferrer">my other posts about SQLite-Net Extensions ORM</a>, where we also covered the other types of relationships that can be modeled using this library.</p>
<p>As this is already the third post from this series, I&#8217;d like to ask you: <span style="text-decoration: underline;"><strong>what do you think about SQLite-Net Extensions ORM? Do you find it useful? Do you use it in your apps? Can you can recommend some other libraries/ORMs to use with SQLite database that allow to model different kind of relationships?</strong></span></p>
<p>The post <a href="https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/">SQLite-Net Extensions – one-to-many relationships</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/sqlite-net-extensions-one-to-many-relationships/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2251</post-id>	</item>
		<item>
		<title>MoneyBack &#8211; 3 weeks before the end of DSP</title>
		<link>https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/</link>
					<comments>https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 09 May 2017 22:09:45 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[moneyback]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2192</guid>

					<description><![CDATA[<p>In today&#8217;s post I&#8217;d like to present what&#8217;s the current status of works on MoneyBack application, 3 weeks before the end of DSP competition. In general, the project hasn&#8217;t been going as well as I expected and is currently not as advanced as I&#8217;d expect it to be at this stage. There are many reasons behind that,&#8230;</p>
<p>The post <a href="https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/">MoneyBack &#8211; 3 weeks before the end of DSP</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In today&#8217;s post I&#8217;d like to present what&#8217;s the current status of works on <em>MoneyBack</em> application, 3 weeks before the end of DSP competition.<br />
<span id="more-2192"></span></p>
<p>In general, the project hasn&#8217;t been going as well as I expected and is currently not as advanced as I&#8217;d expect it to be at this stage. There are many reasons behind that, including lack of time recently and many issues met during development, however, as I already wrote in my <a href="https://www.codejourney.net/2017/02/hello-dajsiepoznac2017/" target="_blank" rel="noopener noreferrer">DSP introducing post</a>, the most important is to survive with the project to the end of the competition and meet all requirements. <span style="text-decoration: underline;">The end of DSP doesn&#8217;t equal the end of <em>MoneyBack</em></span> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>That&#8217;s why in this post I&#8217;d like to show you how the project looks currently and what&#8217;s still to be done. Moreover, as <a href="https://www.codejourney.net/2017/03/using-sqlite-database-in-xamarin-android/" target="_blank" rel="noopener noreferrer">I promised before</a>, <strong>I&#8217;m publishing <a href="https://trello.com/b/pD6NLfH4" target="_blank" rel="noopener noreferrer">my Trello board</a> with tasks still to be done within the project.</strong></p>
<h2>UI changes</h2>
<p>For the last days working on the project I&#8217;ve been trying to make the UI of <em>MoneyBack</em> some kind of &#8220;final&#8221; version, so I can easily extend it adding new functionalities and focus on development instead of spending time on interface design, which is not important for me at the moment. I met many issues with that, which I think came from using some deprecated UI elements I used (e.g. <a href="https://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/" target="_blank" rel="noopener noreferrer">ListView and Adapters</a>) that are not fully-supported in the newest versions of Android. Tutorials are also not really up-to-date for those components. Maybe that&#8217;s also because when I wanted to implement displaying a list of entities I looked in Google for something like &#8220;xamarin android list of elements&#8221; which lead me to this <a href="https://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/" target="_blank" rel="noopener noreferrer">ListView and Adapters</a> tutorial. Instead of firstly reading the whole User Interface tutorial, I wanted to implement displaying the list quickly, so I used those deprecated elements instead of implementing for instance newer and recommended <a href="https://developer.xamarin.com/guides/android/user_interface/recyclerview/" target="_blank" rel="noopener noreferrer">RecyclerView</a> from the beginning, which would be easier extensible now. That definitely teaches me that <strong>I should get to know a particular topic/area better and wider before deciding to use one of the possible solutions to solve a problem</strong>. Sometimes we want to implement something particular quickly, but later it produces more issues than benefits.</p>
<p>Finally I <a href="https://github.com/dsibinski/MoneyBack/commit/db3594f47d10ea543d9a9d2d4869097455590626" target="_blank" rel="noopener noreferrer">added tabs</a> (only one tab for People for now, but it will be easy to add new ones now) and <a href="https://github.com/dsibinski/MoneyBack/commit/386df7738060d8871cca65830ed5ef186ca9e62f" target="_blank" rel="noopener noreferrer">ActionBar menu</a> on the main Activity of the app:</p>
<p><figure id="attachment_2204" aria-describedby="caption-attachment-2204" style="width: 169px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2204" data-permalink="https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/moneyback_mainwithtabs/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?fit=1080%2C1920&amp;ssl=1" data-orig-size="1080,1920" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MoneyBack_MainWithTabs" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?fit=576%2C1024&amp;ssl=1" class="wp-image-2204 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?resize=169%2C300&#038;ssl=1" alt="" width="169" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 169px) 100vw, 169px" /></a><figcaption id="caption-attachment-2204" class="wp-caption-text">MoneyBack &#8211; tabs</figcaption></figure></p>
<p>On the screenshot above, in the right-upper corner there is &#8220;Add&#8221; button visible when clicking on ActionBar menu. It opens a new person&#8217;s adding screen, on which I made name and email fields mandatory:</p>
<p><figure id="attachment_2205" aria-describedby="caption-attachment-2205" style="width: 169px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2205" data-permalink="https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/moneyback_personadding/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?fit=1080%2C1920&amp;ssl=1" data-orig-size="1080,1920" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MoneyBack_PersonAdding" data-image-description="" data-image-caption="&lt;p&gt;MoneyBack &amp;#8211; adding Person&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?fit=576%2C1024&amp;ssl=1" class="size-medium wp-image-2205" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?resize=169%2C300&#038;ssl=1" alt="" width="169" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 169px) 100vw, 169px" /></a><figcaption id="caption-attachment-2205" class="wp-caption-text">MoneyBack &#8211; adding Person</figcaption></figure></p>
<p>People added are then displayed on the main screen of the app in &#8220;People&#8221; tab:</p>
<p><figure id="attachment_2206" aria-describedby="caption-attachment-2206" style="width: 169px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2206" data-permalink="https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/moneyback_list/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?fit=1080%2C1920&amp;ssl=1" data-orig-size="1080,1920" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="MoneyBack_List" data-image-description="" data-image-caption="&lt;p&gt;MoneyBack &amp;#8211; list of people&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?fit=576%2C1024&amp;ssl=1" class="size-medium wp-image-2206" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?resize=169%2C300&#038;ssl=1" alt="" width="169" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 169px) 100vw, 169px" /></a><figcaption id="caption-attachment-2206" class="wp-caption-text">MoneyBack &#8211; list of people</figcaption></figure></p>
<h2>Code &#8211; interesting parts</h2>
<h5>Using tabs layout in an Activity</h5>
<p>It turned out that using tabs-like layout in the Activity is pretty easy. In the AXML layout file for <span style="color: #ff9900;">MainActivity</span> I just added a <span style="color: #ff9900;">FrameLayout</span> container, within which the tabs and their contents are to be displayed:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47515921" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-main-axml" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-xml  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Main.axml content, created by dsibinski on 09:21PM on May 09, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Main.axml">
<tr>
<td id="file-main-axml-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-main-axml-LC1" class="blob-code blob-code-inner js-file-line">&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-main-axml-LC2" class="blob-code blob-code-inner js-file-line">    android:orientation=&quot;vertical&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-main-axml-LC3" class="blob-code blob-code-inner js-file-line">    android:layout_width=&quot;match_parent&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-main-axml-LC4" class="blob-code blob-code-inner js-file-line">    android:layout_height=&quot;match_parent&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-main-axml-LC5" class="blob-code blob-code-inner js-file-line">    android:minWidth=&quot;25px&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-main-axml-LC6" class="blob-code blob-code-inner js-file-line">    android:minHeight=&quot;25px&quot;&gt;</td>
</tr>
<tr>
<td id="file-main-axml-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-main-axml-LC7" class="blob-code blob-code-inner js-file-line">    &lt;FrameLayout</td>
</tr>
<tr>
<td id="file-main-axml-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-main-axml-LC8" class="blob-code blob-code-inner js-file-line">        android:minWidth=&quot;25px&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-main-axml-LC9" class="blob-code blob-code-inner js-file-line">        android:minHeight=&quot;25px&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-main-axml-LC10" class="blob-code blob-code-inner js-file-line">        android:layout_width=&quot;match_parent&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-main-axml-LC11" class="blob-code blob-code-inner js-file-line">        android:layout_height=&quot;match_parent&quot;</td>
</tr>
<tr>
<td id="file-main-axml-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-main-axml-LC12" class="blob-code blob-code-inner js-file-line">        android:id=&quot;@+id/tabFragmentsContainer&quot; /&gt;</td>
</tr>
<tr>
<td id="file-main-axml-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-main-axml-LC13" class="blob-code blob-code-inner js-file-line">&lt;/LinearLayout&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/8871cef3404f1b82834a46b2512c9263/raw/c5d3c8472e50d3f0b4e49921613b6b9abea954e0/Main.axml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/8871cef3404f1b82834a46b2512c9263#file-main-axml" class="Link--inTextBlock"><br />
          Main.axml<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>I called it <span style="color: #ff9900;">tabFragmentsContainer</span>, because within each tab we will display a <span style="color: #000000;"><em>Fragment</em>. <em>Fragment</em> </span>represents a part of UI and/or behavior, which is displayed within an Activity. You can think of Fragments as smaller pieces, that can be placed onto (inside) Activities.</p>
<p>Basically, I changed <span style="color: #ff9900;">PeopleListActivity</span> to <span style="color: #ff9900;">PeopleListFragment</span>, which in fact only required changing inheritance from being a child of <span style="color: #ff9900;">Activity</span> to inheriting from <span style="color: #ff9900;">ListFragment</span> (which is a special kind of <span style="color: #ff9900;">Fragment</span> used for displaying lists of elements). The complete code of <span style="color: #ff9900;">PeopleListFragment</span> can be found <a href="https://gist.github.com/dsibinski/a90e6c8d63e5226dd9c2d3bb1f94db61" target="_blank" rel="noopener noreferrer">in this public Gist</a>.</p>
<p>In the end, making <span style="color: #ff9900;">MainActivity</span> displaying tabs requires setting its ActionBar&#8217;s navigation mode to <span style="color: #ff9900;">ActionBarNavigationMode.Tabs</span>:</p>
<pre><pre class="brush: csharp; title: ; notranslate">this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;</pre>
<p>and adding as many tabs as you wish, using for instance code similar to the following one:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47516212" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-mainactivity_addtab-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="MainActivity_AddTab.cs content, created by dsibinski on 09:31PM on May 09, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="MainActivity_AddTab.cs">
<tr>
<td id="file-mainactivity_addtab-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_addtab-cs-LC1" class="blob-code blob-code-inner js-file-line">void AddTab(string tabText, Fragment view)</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_addtab-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_addtab-cs-LC3" class="blob-code blob-code-inner js-file-line">    var tab = this.ActionBar.NewTab();</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_addtab-cs-LC4" class="blob-code blob-code-inner js-file-line">    tab.SetText(tabText);</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_addtab-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_addtab-cs-LC6" class="blob-code blob-code-inner js-file-line">    tab.TabSelected += delegate (object sender, ActionBar.TabEventArgs e)</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_addtab-cs-LC7" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_addtab-cs-LC8" class="blob-code blob-code-inner js-file-line">        var fragment = this.FragmentManager.FindFragmentById(Resource.Id.tabFragmentsContainer);</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_addtab-cs-LC9" class="blob-code blob-code-inner js-file-line">        if (fragment != null)</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_addtab-cs-LC10" class="blob-code blob-code-inner js-file-line">            e.FragmentTransaction.Remove(fragment);</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-mainactivity_addtab-cs-LC11" class="blob-code blob-code-inner js-file-line">        e.FragmentTransaction.Add(Resource.Id.tabFragmentsContainer, view);</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-mainactivity_addtab-cs-LC12" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-mainactivity_addtab-cs-LC13" class="blob-code blob-code-inner js-file-line">    tab.TabUnselected += delegate (object sender, ActionBar.TabEventArgs e) {</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-mainactivity_addtab-cs-LC14" class="blob-code blob-code-inner js-file-line">        e.FragmentTransaction.Remove(view);</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-mainactivity_addtab-cs-LC15" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-mainactivity_addtab-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-mainactivity_addtab-cs-LC17" class="blob-code blob-code-inner js-file-line">    this.ActionBar.AddTab(tab);</td>
</tr>
<tr>
<td id="file-mainactivity_addtab-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-mainactivity_addtab-cs-LC18" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/621414dcb86e331e87b0ffd12939df1b/raw/36117bd3f8c95db8bba1e8a493ef5835292afbd5/MainActivity_AddTab.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/621414dcb86e331e87b0ffd12939df1b#file-mainactivity_addtab-cs" class="Link--inTextBlock"><br />
          MainActivity_AddTab.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>The arguments are name of the tab and an instance of a <span style="color: #ff9900;">Fragment</span> we want to have displayed in this tab (<span style="color: #ff9900;">PeopleListFragment<span style="color: #000000;">&#8216;s</span></span> instance in our case).</p>
<p>Lines 6-12 present what happens when the tab is selected by the user &#8211; <span style="color: #ff9900;">Fragment</span>&#8216;s instance is added to previously defined <span style="color: #ff9900;">tabFragmentsContainer</span>.</p>
<p>Lines 13-15 define callback method on tab deselection &#8211; <span style="color: #ff9900;">Fragment</span> is removed from the container.</p>
<h5>Adding ActionBar with menu to the Activity</h5>
<p>Addition of ActionBar with menu button in right-upper corner of the Activity requires creating an XML view in Resources/menu folder first (with one button in our case):</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47516362" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-actionbarmenu-xml" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-xml  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="ActionBarMenu.xml content, created by dsibinski on 09:37PM on May 09, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="ActionBarMenu.xml">
<tr>
<td id="file-actionbarmenu-xml-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-actionbarmenu-xml-LC1" class="blob-code blob-code-inner js-file-line">&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;</td>
</tr>
<tr>
<td id="file-actionbarmenu-xml-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-actionbarmenu-xml-LC2" class="blob-code blob-code-inner js-file-line">  &lt;item android:id=&quot;@+id/menuAdd&quot;</td>
</tr>
<tr>
<td id="file-actionbarmenu-xml-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-actionbarmenu-xml-LC3" class="blob-code blob-code-inner js-file-line">        android:title=&quot;@string/menuAddTitle&quot;/&gt;</td>
</tr>
<tr>
<td id="file-actionbarmenu-xml-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-actionbarmenu-xml-LC4" class="blob-code blob-code-inner js-file-line">&lt;/menu&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/5bf6c6753228cbe52b38e4aba429cacb/raw/3d4dafa8cc94ab3f754787097609cd81b4e30e4a/ActionBarMenu.xml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/5bf6c6753228cbe52b38e4aba429cacb#file-actionbarmenu-xml" class="Link--inTextBlock"><br />
          ActionBarMenu.xml<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and then in the Activity considered overriding <span style="color: #ff9900;">OnCreateOptionsMenu</span> method inflating ActionBar&#8217;s menu using created view:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47516393" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-mainactivity_oncreateoptionsmenu-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="MainActivity_OnCreateOptionsMenu.cs content, created by dsibinski on 09:39PM on May 09, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="MainActivity_OnCreateOptionsMenu.cs">
<tr>
<td id="file-mainactivity_oncreateoptionsmenu-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_oncreateoptionsmenu-cs-LC1" class="blob-code blob-code-inner js-file-line">public override bool OnCreateOptionsMenu(IMenu menu)</td>
</tr>
<tr>
<td id="file-mainactivity_oncreateoptionsmenu-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_oncreateoptionsmenu-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_oncreateoptionsmenu-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_oncreateoptionsmenu-cs-LC3" class="blob-code blob-code-inner js-file-line">    MenuInflater.Inflate(Resource.Menu.ActionBarMenu, menu);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreateoptionsmenu-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_oncreateoptionsmenu-cs-LC4" class="blob-code blob-code-inner js-file-line">    return base.OnPrepareOptionsMenu(menu);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreateoptionsmenu-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_oncreateoptionsmenu-cs-LC5" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/4053bd9d9aaf8d28fbf6960b1a5855df/raw/7e6a1422dfa2eccbd8936ff28bbdf0ee4ea6ec99/MainActivity_OnCreateOptionsMenu.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/4053bd9d9aaf8d28fbf6960b1a5855df#file-mainactivity_oncreateoptionsmenu-cs" class="Link--inTextBlock"><br />
          MainActivity_OnCreateOptionsMenu.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>We also need to define what happens when a menu option is selected. For that purpose, override <span style="color: #ff9900;">OnOptionsItemSelected</span> method:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47516427" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-mainactivity_onoptionsitemselected-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="MainActivity_OnOptionsItemSelected.cs content, created by dsibinski on 09:40PM on May 09, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="MainActivity_OnOptionsItemSelected.cs">
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC1" class="blob-code blob-code-inner js-file-line">public override bool OnOptionsItemSelected(IMenuItem item)</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC3" class="blob-code blob-code-inner js-file-line">    if (item.ItemId == Resource.Id.menuAdd)</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC5" class="blob-code blob-code-inner js-file-line">        OpenAddingNewPerson();</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC6" class="blob-code blob-code-inner js-file-line">        return true;</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC7" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC9" class="blob-code blob-code-inner js-file-line">    return base.OnOptionsItemSelected(item);</td>
</tr>
<tr>
<td id="file-mainactivity_onoptionsitemselected-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_onoptionsitemselected-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/80803c442ea4c4027bc5db86b7a528da/raw/9d380aa4d43cf8d20a6d47ca8323d2e147d7423a/MainActivity_OnOptionsItemSelected.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/80803c442ea4c4027bc5db86b7a528da#file-mainactivity_onoptionsitemselected-cs" class="Link--inTextBlock"><br />
          MainActivity_OnOptionsItemSelected.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<h2>Next coding tasks</h2>
<p>From now on you can watch <a href="https://trello.com/b/pD6NLfH4" target="_blank" rel="noopener noreferrer">my public Trello board</a>, where I have all tasks to be done in the nearest future in <em>MoneyBack</em> defined. I will try to define deadlines for those tasks as well.</p>
<p>At the moment of writing this post, <a href="https://github.com/dsibinski/MoneyBack/commit/d6f58805dc8f9e8c0b303cf8ecbfd3bbf4930aff" target="_blank" rel="noopener noreferrer">I&#8217;ve started adding a possibility to create Events</a>. I will need to keep many-to-many relationship between Person and Event entities and I will probably use <a href="https://bitbucket.org/twincoders/sqlite-net-extensions" target="_blank" rel="noopener noreferrer">SQLite-Net Extensions</a> library for that. You can expect a separate post about defining relationships using this library soon <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Other tasks left to be done</h2>
<p>Apart from coding and developing the project, I still need to fulfill the <a href="https://www.codejourney.net/2017/02/hello-dajsiepoznac2017/" target="_blank" rel="noopener noreferrer">DSP competition&#8217;s requirements</a>. This is my 14th post within <a href="https://www.codejourney.net/category/dajsiepoznac2017/" target="_blank" rel="noopener noreferrer">DajSiePoznac2017</a>, so 6 posts still to be written. I have the ideas in my mind already and few next posts planned. There are only 3 weeks left to the end of the competition, so those days will need to be more intensive that it recently was, but that&#8217;s good, it means that you should be receiving more content here in the coming days and I will be spending more time on developing <em>MoneyBack</em>. Only positive changes, I hope <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Summary</h2>
<p>We saw the status of <em>MoneyBack</em> project today. There are still many things to be done in the app to at least fulfill the minimal requirements I assumed in the beginning of the competition. but as I mentioned, the end of DSP is not the end of <em>MoneyBack</em> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> On the other hand, DSP is a very good motivator, so I&#8217;ll try to make coming days and weeks more intensive. The most important goal for now is to fulfill the competition&#8217;s requirements for having 20 posts written until the end of May, which shouldn&#8217;t be problematic at all <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>I&#8217;ve also published my Trello dashboard. You can find a link to it <a href="https://www.codejourney.net/dajsiepoznac-2017/" target="_blank" rel="noopener noreferrer">here</a>.</p>
<p>Using this opportunity, I&#8217;d like to wish all DSP&#8217;17 participants good luck in the last weeks of the competition. I&#8217;m constantly reading the others&#8217; blogs and I see a lot of very nice and decent quality stuff appearing in Polish programming community on your blogs and repositories &#8211; great job!</p>
<p>Keep your fingers crossed! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/">MoneyBack &#8211; 3 weeks before the end of DSP</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/moneyback-3-weeks-before-the-end-of-dsp/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2192</post-id>	</item>
		<item>
		<title>Solving performance issues with dotTrace</title>
		<link>https://www.codejourney.net/solving-performance-issues-with-dottrace/</link>
					<comments>https://www.codejourney.net/solving-performance-issues-with-dottrace/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 12 Mar 2017 14:40:24 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[performance]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=728</guid>

					<description><![CDATA[<p>If you&#8217;ve ever had any performance issues with your .NET applications, you may find this writing interesting. In this post I&#8217;d like to present to you a tool produced by JetBrains &#8211; dotTrace, showing how using only one of its functionalities can help in finding causes of performance issues in .NET applications. Performance issue on production Months&#8230;</p>
<p>The post <a href="https://www.codejourney.net/solving-performance-issues-with-dottrace/">Solving performance issues with dotTrace</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>If you&#8217;ve ever had any performance issues with your .NET applications, you may find this writing interesting.</p>
<p>In this post I&#8217;d like to present to you a tool produced by JetBrains &#8211; <strong>dotTrace</strong>, showing how using only one of its functionalities can help in finding causes of performance issues in .NET applications.<br />
<span id="more-728"></span></p>
<h2>Performance issue on production</h2>
<p>Months ago some of your colleagues implemented an application and delivered it to the Customer. The app is &#8220;Countries and Cities Manager&#8221;, which is used by some administrator working in local government unit. That&#8217;s how it looks:</p>
<p><figure id="attachment_735" aria-describedby="caption-attachment-735" style="width: 380px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="735" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/countriesandcitiesmanager/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?fit=646%2C232&amp;ssl=1" data-orig-size="646,232" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="countriesAndCitiesManager" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?fit=646%2C232&amp;ssl=1" class="wp-image-735 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?resize=380%2C137&#038;ssl=1" alt="" width="380" height="137" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?resize=300%2C108&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?w=646&amp;ssl=1 646w" sizes="auto, (max-width: 380px) 100vw, 380px" /></a><figcaption id="caption-attachment-735" class="wp-caption-text">Countries and Cities Manager</figcaption></figure></p>
<p>That&#8217;s cool, isn&#8217;t it ? This &#8220;administration panel&#8221; allows to add a new city to the country. User fills name of the city and provides ISO code of the country considered. You may think &#8220;who would ever use it and for what?&#8221;. True. But first of all, this is just an example <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , and secondly, imagine that Russia annexes some big European country. What happens then ? User administrating local government system must use your manager application to insert hundreds or thousands of new cities in Russia. Gotcha!</p>
<p>The next day you receive a ticket in your company&#8217;s issues tracking system. Taking into consideration that an average number of cities in east-European countries is ~600, the ticket&#8217;s priority is set to &#8220;Blocking&#8221;. The description of the issue is:</p>
<ol>
<li>User fills the &#8220;City&#8221; and &#8220;Country ISO Code&#8221;, clicks &#8220;Add city&#8221;</li>
<li>Waits for 10 seconds&#8230;</li>
<li>Waits for 20 seconds&#8230;</li>
<li>Waits for 30 seconds&#8230;</li>
<li>Error message received:<br />
<figure id="attachment_738" aria-describedby="caption-attachment-738" style="width: 395px" class="wp-caption alignnone"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="738" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/errorisonotfound/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/errorISONotFound.png?fit=702%2C319&amp;ssl=1" data-orig-size="702,319" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="errorISONotFound" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/errorISONotFound.png?fit=702%2C319&amp;ssl=1" class="wp-image-738 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/errorISONotFound.png?resize=395%2C179&#038;ssl=1" alt="" width="395" height="179" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/errorISONotFound.png?resize=300%2C136&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/errorISONotFound.png?w=702&amp;ssl=1 702w" sizes="auto, (max-width: 395px) 100vw, 395px" /><figcaption id="caption-attachment-738" class="wp-caption-text">ISO not found</figcaption></figure>
</li>
<li>User corrects &#8220;RU&#8221; to &#8220;RUS&#8221;
<div class="mceTemp"> </div>
</li>
<li>Waits for 10 seconds&#8230;</li>
<li>Waits for 20 seconds&#8230;</li>
<li>Waits for 30 seconds&#8230;</li>
<li> City added!</li>
<li>Scenario repeats for each new city to be added. Performance is unacceptable.</li>
</ol>
<p>Initially you have no idea what could be the reason. Such simple operation and such terrible performance? Let&#8217;s see&#8230;</p>
<h2>Looking for issue with dotTrace profiling</h2>
<p>In such cases, especially if I don&#8217;t know the code of the application considered, the very first thing I do it to use <a href="https://www.jetbrains.com/profiler/" target="_blank" rel="noopener"><strong>dotTrace</strong></a> in order to profile the application when executing bad-performance actions. It provides many features, including:</p>
<ul>
<li>detecting performance bottlenecks in .NET applications</li>
<li>getting information about calls execution times</li>
<li>analyzing calls order on a timeline</li>
<li>profilling SQL queries and HTTP requests</li>
<li>profiling unit tests</li>
<li>&#8230; and <a href="https://www.jetbrains.com/profiler/" target="_blank" rel="noopener">many more</a>.</li>
</ul>
<p>We will use only the simplest profiling mode which is called <em>Sampling</em>.</p>
<p>After you <a href="https://www.jetbrains.com/profiler/" target="_blank" rel="noopener">downloaded and installed dotTrace</a>, launch the application you want to profile first. Then, launch <em>dotTrace </em>and in <em>Attach to Process</em> section find and select process of your app and select <em>Sampling</em> mode:</p>
<p><figure id="attachment_740" aria-describedby="caption-attachment-740" style="width: 514px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="740" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/dottrace_attaching/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?fit=1245%2C583&amp;ssl=1" data-orig-size="1245,583" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="dotTrace_attaching" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?fit=1024%2C480&amp;ssl=1" class="wp-image-740" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?resize=514%2C240&#038;ssl=1" alt="" width="514" height="240" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?resize=300%2C140&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?resize=768%2C360&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?resize=1024%2C480&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?resize=720%2C337&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?w=1245&amp;ssl=1 1245w" sizes="auto, (max-width: 514px) 100vw, 514px" /></a><figcaption id="caption-attachment-740" class="wp-caption-text">dotTrace &#8211; Sampling mode</figcaption></figure></p>
<p>Then, click &#8220;Run&#8221; button just below <em>Sampling </em>mode selection &#8211; you&#8217;ll see the profiling session has started:</p>
<p><figure id="attachment_742" aria-describedby="caption-attachment-742" style="width: 402px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="742" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/dottrace_session_running/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?fit=826%2C122&amp;ssl=1" data-orig-size="826,122" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="dotTrace_session_running" data-image-description="" data-image-caption="&lt;p&gt;dotTrace session&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?fit=826%2C122&amp;ssl=1" class=" wp-image-742" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?resize=402%2C59&#038;ssl=1" alt="" width="402" height="59" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?resize=300%2C44&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?resize=768%2C113&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?resize=720%2C106&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?w=826&amp;ssl=1 826w" sizes="auto, (max-width: 402px) 100vw, 402px" /></a><figcaption id="caption-attachment-742" class="wp-caption-text">dotTrace session</figcaption></figure></p>
<p>Next, go to your application and execute bad-performance action. In our case, we click on &#8220;Add city&#8221; button:</p>
<p><figure id="attachment_779" aria-describedby="caption-attachment-779" style="width: 460px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="779" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/addcity_click-4/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?fit=430%2C154&amp;ssl=1" data-orig-size="430,154" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="addCity_Click" data-image-description="" data-image-caption="&lt;p&gt;Add City clicked&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?fit=430%2C154&amp;ssl=1" class=" wp-image-779" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?resize=460%2C164&#038;ssl=1" alt="" width="460" height="164" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?resize=300%2C107&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?w=430&amp;ssl=1 430w" sizes="auto, (max-width: 460px) 100vw, 460px" /></a><figcaption id="caption-attachment-779" class="wp-caption-text">Add City clicked</figcaption></figure></p>
<p>App is not responding &#8211; cool! Now we wait those 10, 20, 30 seconds until we get the error message described by the user. To be sure what&#8217;s happening, we can click the button few more times (maybe the next executions are better?). I clicked it 3 times are the times were pretty the same.</p>
<p>That&#8217;s the end of our bad-performance action, so in <em>dotTrace</em> session&#8217;s window click &#8220;Get Snapshot and Wait&#8221;:</p>
<p><figure id="attachment_744" aria-describedby="caption-attachment-744" style="width: 460px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="744" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/dottrace_getsnapshot/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?fit=828%2C159&amp;ssl=1" data-orig-size="828,159" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="dotTrace_GetSnapshot" data-image-description="&lt;p&gt;dotTrace &amp;#8211; getting snapshot&lt;/p&gt;
" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?fit=828%2C159&amp;ssl=1" class="wp-image-744 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?resize=460%2C89&#038;ssl=1" alt="" width="460" height="89" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?resize=300%2C58&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?resize=768%2C147&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?resize=720%2C138&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?w=828&amp;ssl=1 828w" sizes="auto, (max-width: 460px) 100vw, 460px" /></a><figcaption id="caption-attachment-744" class="wp-caption-text">dotTrace &#8211; getting snapshot</figcaption></figure></p>
<p>After few seconds, <em>JetBrains dotTrace Performance Viewer</em> opens. Open &#8220;Threads Tree&#8221; on &#8220;All Calls&#8221; tab:</p>
<p><figure id="attachment_747" aria-describedby="caption-attachment-747" style="width: 435px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="747" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/perfviewer_threadstree/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?fit=709%2C326&amp;ssl=1" data-orig-size="709,326" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="perfViewer_ThreadsTree" data-image-description="" data-image-caption="&lt;p&gt;Threads Tree&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?fit=709%2C326&amp;ssl=1" class=" wp-image-747" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?resize=435%2C200&#038;ssl=1" alt="" width="435" height="200" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?resize=300%2C138&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?w=709&amp;ssl=1 709w" sizes="auto, (max-width: 435px) 100vw, 435px" /></a><figcaption id="caption-attachment-747" class="wp-caption-text">Threads Tree</figcaption></figure></p>
<p>In this section we normally see all the threads running within our application during profiling time. We had only one thread, so let&#8217;s expand the details to see the time and percentage duration of particular calls from the calls stack:</p>
<p><figure id="attachment_748" aria-describedby="caption-attachment-748" style="width: 665px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="748" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/perfviewer_longestcall/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?fit=1269%2C311&amp;ssl=1" data-orig-size="1269,311" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="perfViewer_LongestCall" data-image-description="" data-image-caption="&lt;p&gt;Calls duration in performance viewer&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?fit=1024%2C251&amp;ssl=1" class=" wp-image-748" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?resize=665%2C164&#038;ssl=1" alt="" width="665" height="164" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?resize=300%2C74&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?resize=768%2C188&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?resize=1024%2C251&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?resize=720%2C176&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?w=1269&amp;ssl=1 1269w" sizes="auto, (max-width: 665px) 100vw, 665px" /></a><figcaption id="caption-attachment-748" class="wp-caption-text">Calls duration in performance viewer</figcaption></figure></p>
<p>At this moment, without even opening the code, we already see that method called <em>GetAllEuropeanCountries</em> takes <strong>83.63%</strong> of our thread&#8217;s execution time. What&#8217;s more, we can see that this method is defined in <strong><em>CountriesCitiesDbService</em></strong><strong> </strong>which apperently retrieves list of European countries from the database or some external source.</p>
<p>The most percipient of you probably noticed there is <em>Thread.Sleep(Int32) </em>method called one level down &#8211; yes, that&#8217;s for example&#8217;s purposes <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , but in real world this would be a database query or a web service call here. The most important is that we know what takes the longest during our operation. Let&#8217;s now fix it!</p>
<h2>Fixing the issue</h2>
<p>Let&#8217;s open <em>CountriesCitiesManager</em> solution and use the knowledge we already have from the profiling. We go to the <em>AddNewCity(String, String)</em> method, in which the method for getting countries was called (this is deductible from the calls tree in performance viewer). Here&#8217;s the code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45629395" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-addnewcity-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="AddNewCity.cs content, created by dsibinski on 01:02PM on March 12, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="AddNewCity.cs">
<tr>
<td id="file-addnewcity-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-addnewcity-cs-LC1" class="blob-code blob-code-inner js-file-line">private bool AddNewCity(string cityName, string countryIso)</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-addnewcity-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-addnewcity-cs-LC3" class="blob-code blob-code-inner js-file-line">    var city = CountriesCitiesDbService.GetNewCity();</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-addnewcity-cs-LC4" class="blob-code blob-code-inner js-file-line">    var europeanCountries = CountriesCitiesDbService.GetAllEuropeanCountries();</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-addnewcity-cs-LC5" class="blob-code blob-code-inner js-file-line">    var country = europeanCountries.FirstOrDefault(ec =&gt; ec.IsoCode.Equals(countryIso));</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-addnewcity-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-addnewcity-cs-LC7" class="blob-code blob-code-inner js-file-line">    if (country == null)</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-addnewcity-cs-LC8" class="blob-code blob-code-inner js-file-line">        throw new ArgumentException($&quot;Country with ISO Code {countryIso} does not exist!&quot;);</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-addnewcity-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-addnewcity-cs-LC10" class="blob-code blob-code-inner js-file-line">    city.Name = cityName;</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-addnewcity-cs-LC11" class="blob-code blob-code-inner js-file-line">    city.Country = country;</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-addnewcity-cs-LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-addnewcity-cs-LC13" class="blob-code blob-code-inner js-file-line">    CountriesCitiesDbService.SaveCity(city);</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-addnewcity-cs-LC14" class="blob-code blob-code-inner js-file-line">    return true;</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-addnewcity-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addnewcity-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-addnewcity-cs-LC16" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/9e459fb3d6cd16567fc09f90ba948efb/raw/716d4066a91294a0b47dc8a30432887a07906b4e/AddNewCity.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/9e459fb3d6cd16567fc09f90ba948efb#file-addnewcity-cs" class="Link--inTextBlock"><br />
          AddNewCity.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><em>AddNewCity</em> method is called every time the &#8220;Add city&#8221; button is pressed. In line number 4. we are getting the list of all 46 European countries:</p>
<p><figure id="attachment_754" aria-describedby="caption-attachment-754" style="width: 483px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="754" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/getalleucountrieslist/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?fit=839%2C63&amp;ssl=1" data-orig-size="839,63" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="getAllEUCountriesList" data-image-description="" data-image-caption="&lt;p&gt;Variable storing 46 EU countries&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?fit=839%2C63&amp;ssl=1" class="wp-image-754 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?resize=483%2C37&#038;ssl=1" alt="" width="483" height="37" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?resize=300%2C23&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?resize=768%2C58&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?resize=720%2C54&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?w=839&amp;ssl=1 839w" sizes="auto, (max-width: 483px) 100vw, 483px" /></a><figcaption id="caption-attachment-754" class="wp-caption-text">Variable storing 46 EU countries</figcaption></figure></p>
<p>How probable it is that the number of countries in Europe changes during our application&#8217;s runtime? Very close to 0, I&#8217;d say. <strong>So there is totally no sense in retrieving the list of EU countries (from the DB, web service or whatever) every time the button is clicked!</p>
<p></strong></p>
<p>We need to cache this list somehow. Let&#8217;s simply extract the variable for storing EU countries as read-only class property initialized only when used for the first time:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45630185" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-europeancitiesproperty-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="EuropeanCitiesProperty.cs content, created by dsibinski on 01:50PM on March 12, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="EuropeanCitiesProperty.cs">
<tr>
<td id="file-europeancitiesproperty-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-europeancitiesproperty-cs-LC1" class="blob-code blob-code-inner js-file-line">private List&lt;Country&gt; _europeanCountries;</td>
</tr>
<tr>
<td id="file-europeancitiesproperty-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-europeancitiesproperty-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-europeancitiesproperty-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-europeancitiesproperty-cs-LC3" class="blob-code blob-code-inner js-file-line">public List&lt;Country&gt; EuropeanCountries =&gt; </td>
</tr>
<tr>
<td id="file-europeancitiesproperty-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-europeancitiesproperty-cs-LC4" class="blob-code blob-code-inner js-file-line">    _europeanCountries ?? (_europeanCountries = CountriesCitiesDbService.GetAllEuropeanCountries());</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/5c1d7f2e77f61ac081d6b20f4cf1f86b/raw/4e3bc93235f938e4e0b2f0ac9473186230e3fe2f/EuropeanCitiesProperty.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/5c1d7f2e77f61ac081d6b20f4cf1f86b#file-europeancitiesproperty-cs" class="Link--inTextBlock"><br />
          EuropeanCitiesProperty.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and use it in <em>AddNewCity</em> method:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45630262" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-addnewcity_corrected-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="AddNewCity_Corrected.cs content, created by dsibinski on 01:54PM on March 12, 2017."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" data-component="Octicon" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="AddNewCity_Corrected.cs">
<tr>
<td id="file-addnewcity_corrected-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-addnewcity_corrected-cs-LC1" class="blob-code blob-code-inner js-file-line">private bool AddNewCity(string cityName, string countryIso)</td>
</tr>
<tr>
<td id="file-addnewcity_corrected-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-addnewcity_corrected-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-addnewcity_corrected-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-addnewcity_corrected-cs-LC3" class="blob-code blob-code-inner js-file-line">    var city = CountriesCitiesDbService.GetNewCity();</td>
</tr>
<tr>
<td id="file-addnewcity_corrected-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-addnewcity_corrected-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addnewcity_corrected-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-addnewcity_corrected-cs-LC5" class="blob-code blob-code-inner js-file-line">    var country = EuropeanCountries.FirstOrDefault(ec =&gt; ec.IsoCode.Equals(countryIso));</td>
</tr>
<tr>
<td id="file-addnewcity_corrected-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-addnewcity_corrected-cs-LC6" class="blob-code blob-code-inner js-file-line">    // the rest of method&#39;s code&#8230;</td>
</tr>
<tr>
<td id="file-addnewcity_corrected-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-addnewcity_corrected-cs-LC7" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/e767ddb0a04208ba01729e0c460ca537/raw/0b61f0394e1fe7f7f5e37c8e7a89d603b59f010d/AddNewCity_Corrected.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e767ddb0a04208ba01729e0c460ca537#file-addnewcity_corrected-cs" class="Link--inTextBlock"><br />
          AddNewCity_Corrected.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>When the application is now launched, s<em>ampling </em>started and button clicked 3 times, we already see the improvement:</p>
<p><figure id="attachment_759" aria-describedby="caption-attachment-759" style="width: 707px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="759" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/perfviewer_corrected1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?fit=1265%2C296&amp;ssl=1" data-orig-size="1265,296" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="perfViewer_Corrected1" data-image-description="" data-image-caption="&lt;p&gt;Calls after improvement&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?fit=1024%2C240&amp;ssl=1" class=" wp-image-759" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?resize=707%2C165&#038;ssl=1" alt="" width="707" height="165" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?resize=300%2C70&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?resize=768%2C180&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?resize=1024%2C240&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?resize=720%2C168&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?w=1265&amp;ssl=1 1265w" sizes="auto, (max-width: 707px) 100vw, 707px" /></a><figcaption id="caption-attachment-759" class="wp-caption-text">Calls after improvement</figcaption></figure></p>
<p><em>AddNewCity</em> takes <strong>65.96%</strong> now. This is average value from all the calls we made, so let&#8217;s now perform <em>sampling</em> starting from the 2nd click:</p>
<p><figure id="attachment_761" aria-describedby="caption-attachment-761" style="width: 762px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="761" data-permalink="https://www.codejourney.net/solving-performance-issues-with-dottrace/perfviewer_corrected2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?fit=1271%2C277&amp;ssl=1" data-orig-size="1271,277" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="perfViewer_Corrected2" data-image-description="" data-image-caption="&lt;p&gt;Performance omitting 1st click&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?fit=1024%2C223&amp;ssl=1" class=" wp-image-761" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?resize=762%2C165&#038;ssl=1" alt="" width="762" height="165" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?resize=300%2C65&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?resize=768%2C167&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?resize=1024%2C223&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?resize=720%2C157&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?w=1271&amp;ssl=1 1271w" sizes="auto, (max-width: 762px) 100vw, 762px" /></a><figcaption id="caption-attachment-761" class="wp-caption-text">Performance omitting 1st click</figcaption></figure></p>
<p>The whole <em>AddNewCity</em> method is now taking only <strong>0.41% of the calls</strong> during the operation.</p>
<p>Now, if we want to make Customer&#8217;s life beautiful, we&#8217;d extract initialization of EU countries list to another thread, so it can happen when the application launches and UI is not frozen. We will however stop here. You get the idea, don&#8217;t you ? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Summary</h2>
<p>Today we&#8217;ve seen how easily &#8211; by performing just the simplest profiling session that can be done in <em>dotTrace </em>&#8211; it may be to detect what causes real performance issues in .NET application. Of course the example was pretty naive and simple, but I didn&#8217;t make it up &#8211; many times I&#8217;ve already worked with performance issues in production code which were caused by retrieving so called &#8220;dictionary&#8221; or static data using some API or database connection every time in a loop or repetitive process, which was totally unnecessary. By only implementing some kind of cache (maybe a bit more reasonable than the one we did, which in our case was actually enough), I managed to optimize processes executing time from 3 or 4 hours to several seconds.</p>
<p>Obviously if you&#8217;re an experienced developer, you&#8217;d probably identify such places in which caching or similar mechanism should be used when writing code. Profiling may however be useful for less experienced programmers or when working with legacy code we didn&#8217;t write (or we wrote months or years ago <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ). It doesn&#8217;t cost much, except the cost of <em>dotTrace </em>itself, which is a part of <a href="https://www.jetbrains.com/resharper/buy/index.jsp?product=ultimate#edition=commercial" target="_blank" rel="noopener">ReSharper Ultimate</a>, but this tool is just an example, you are not limited to it. For sure there are many other tools that offer the same (or maybe even more?) functionalities.</p>
<p><span style="text-decoration: underline;"><strong>What are the tools you use for debugging performance issues ? Maybe you also use <em>dotTrace</em>, but can share some experience in using its other functionalities?</strong></span></p>
<p>The post <a href="https://www.codejourney.net/solving-performance-issues-with-dottrace/">Solving performance issues with dotTrace</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/solving-performance-issues-with-dottrace/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">728</post-id>	</item>
		<item>
		<title>Building Windows Services using Topshelf</title>
		<link>https://www.codejourney.net/windows-services-using-topshelf/</link>
					<comments>https://www.codejourney.net/windows-services-using-topshelf/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 14 May 2016 18:19:52 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[topshelf]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=26</guid>

					<description><![CDATA[<p>Hello again 🙂 Visibly this is going to be my first technical post here. I hope you&#8217;ll find it useful. Windows Services Recently I came up with a need to create an application, which executes some tasks in the background based on file system&#8217;s events. &#8220;That&#8217;s easy&#8221;, one would say. &#8220;Build Windows Service app&#8221;, he&#8230;</p>
<p>The post <a href="https://www.codejourney.net/windows-services-using-topshelf/">Building Windows Services using Topshelf</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p style="text-align: left;">Hello again 🙂<br />
Visibly this is going to be my first technical post here. I hope you&#8217;ll find it useful.</p>
<p><span id="more-26"></span></p>
<h2>Windows Services</h2>
<p style="text-align: left;">Recently I came up with a need to create an application, which executes some tasks in the background based on file system&#8217;s events. &#8220;That&#8217;s easy&#8221;, one would say. &#8220;Build Windows Service app&#8221;, he would add. Sure, that was also my first idea.</p>
<p style="text-align: left;">I think that&#8217;s very common that we want to create an application without any GUI, which purpose is just to do something in the background. Moreover we&#8217;d like it to be independent from the user running it &#8211; we want it to be running all the time, without having to manually launch it &#8211; especially when the application is running on customer&#8217;s environment, where we can&#8217;t be logged in all the time running the application.</p>
<p style="text-align: left;">Here comes the service &#8211; long-running executable with no user interface, which runs in its own Windows session. Such application can be:</p>
<ul>
<li style="text-align: left;">executed by any user created in the system (e.g. with specific security policies assigned),</li>
<li style="text-align: left;">started automatically when the system launches,</li>
<li style="text-align: left;">automatically restarted in case of errors,</li>
<li style="text-align: left;">at any time started, paused, stopped or restarted.</li>
</ul>
<p style="text-align: left;">Even if you&#8217;ve never developed any service applications, you are using many of them &#8211; check your <em>services.msc</em><code></code> to see the list of services currently running in your system.</p>
<h2>Topshelf</h2>
<p style="text-align: left;">Visual Studio 2015 provides a template to create Windows Service application and probably I could finish my post here. However, I would like to share with you an <strong>even easier</strong> way of building services: to do it with <em>Topshelf</em> &#8211; a very lightweight open-source library, which purpose it to make services development, debugging and deployment painless. <em>Topshelf</em> allows the developer to focus on service&#8217;s functionality, instead of wasting time interacting with .NET Framework&#8217;s build-in services support. There is also no more need to install your service using <em>InstallUtil </em>or learn how to attach your Visual Studio debugger to running service to detect issues.</p>
<p style="text-align: left;">Using <em>Topshelf</em> it&#8217;s enough to create console application, add one service class with public <code>Start</code> and <code>Stop</code> methods, configure service&#8217;s startup parameters (its name, display name, description etc.) and you&#8217;re ready to go. Below we&#8217;ll see how to do it.</p>
<h2 style="text-align: left;">Creating Windows Service application</h2>
<p style="text-align: left;">After creating console application in Visual Studio, add <em>Topshelf</em> to the project by installing it from <em>Nuget</em>:</p>
<p style="text-align: left;"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="51" data-permalink="https://www.codejourney.net/windows-services-using-topshelf/attachment/1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?fit=955%2C91&amp;ssl=1" data-orig-size="955,91" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Topshelf &amp;#8211; Nuget" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?fit=955%2C91&amp;ssl=1" class="alignleft size-full wp-image-51" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?resize=955%2C91&#038;ssl=1" alt="Topshelf - Nuget" width="955" height="91" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?w=955&amp;ssl=1 955w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?resize=300%2C29&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?resize=768%2C73&amp;ssl=1 768w" sizes="auto, (max-width: 955px) 100vw, 955px" /></a></p>
<h2 style="text-align: left;">Adding service class</h2>
<p style="text-align: left;">Then, create service class, which is responsible for executing your service&#8217;s logic:</p>
<pre><pre class="brush: csharp; title: ; notranslate">
class FileWatcherService
{
   public bool Start()
   {
      // Initialize your service application here
      return true;
   }


   public bool Stop()
   {
      // Executed when the service is stopped
      // Dispose your objects here etc.
      return true;
   }
}
</pre>
<p style="text-align: left;">Both of those methods return <code>boolean</code> to indicate that starting/stopping of the service completed successfully.</p>
<h2 style="text-align: left;">Adding service configuration</h2>
<p style="text-align: left;">Now we only need to configure the service&#8217;s parameters. <em>Topshelf</em> provides <code>HostFactory</code> class which contains <code>Run</code> method, to which we can pass fluently-created set of settings:</p>
<ul style="text-align: left;">
<li>service class instance,</li>
<li>methods to be executed while the service is started/stopped/paused/continued,</li>
<li>service&#8217;s name, display name, description,</li>
<li>start/stop timeouts,</li>
<li>startup type (automatic, manual, automatic delayed),</li>
<li>&#8230; <a href="http://docs.topshelf-project.com/en/latest/configuration/config_api.html">and many more</a>.</li>
</ul>
<p style="text-align: left;">The set-up code should be put in the <code>Main</code> method of <code>Program.cs</code>. In our case, the simplest configuration could look as follows:</p>
<pre><pre class="brush: csharp; title: ; notranslate">
static void Main(string&#x5B;] args)
{
    HostFactory.Run(serviceConfig =&amp;amp;amp;amp;amp;gt;
    {
        serviceConfig.Service&amp;amp;amp;amp;amp;lt;FileWatcherService&amp;amp;amp;amp;amp;gt;(serviceInstance =&amp;amp;amp;amp;amp;gt;
        {
            serviceInstance.ConstructUsing(() =&amp;amp;amp;amp;amp;gt; new FileWatcherService());
            serviceInstance.WhenStarted(execute =&amp;amp;amp;amp;amp;gt; execute.Start());
            serviceInstance.WhenStopped(execute =&amp;amp;amp;amp;amp;gt; execute.Stop());
        });

        serviceConfig.SetServiceName(&quot;FileWatcherService&quot;);
        serviceConfig.SetDisplayName(&quot;File Watcher Service&quot;);
        serviceConfig.SetDescription(&quot;Service monitoring local folders for file system events&quot;);
        serviceConfig.StartAutomatically();

    });
}
</pre>
<h2 style="text-align: left;">Debugging the service</h2>
<p style="text-align: left;">Ease of implementation and configuration of the service application isn&#8217;t the only benefit of using <em>Topshelf</em>. Our application has been created as a console app, so it can be simply run and debugged by using F5 button. No more need to attach debugger to the service itself 🙂</p>
<h2 style="text-align: left;">Installing the service</h2>
<p style="text-align: left;"><em>Topshelf</em> also adds some &#8220;shell layer&#8221; to our application. To install executable file (which is the output of our console application) into Windows Service Control Manager (SCM) to be running as a &#8220;real&#8221; Windows Service, it&#8217;s enough to open the command line, navigate to the folder where the <em>.exe</em> file is present and install it passing <code>install</code> as <em>.exe&#8217;s</em> parameter (e.g.: <code>FileWatcherService.exe install)</code>. After executing it, we can see our service created by looking into <i>services.msc</i>:</p>
<p style="text-align: left;"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="72" data-permalink="https://www.codejourney.net/windows-services-using-topshelf/attachment/2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?fit=1283%2C125&amp;ssl=1" data-orig-size="1283,125" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Installed service" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?fit=1024%2C100&amp;ssl=1" class="size-full wp-image-72 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?resize=1140%2C111&#038;ssl=1" alt="Installed service" width="1140" height="111" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?w=1283&amp;ssl=1 1283w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?resize=300%2C29&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?resize=768%2C75&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?resize=1024%2C100&amp;ssl=1 1024w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></a></p>
<p>
It&#8217;s similarly easy to uninstall the service.</p>
<h2 style="text-align: left;">Not only Windows</h2>
<p style="text-align: left;">The official <i>Topshelf&#8217;s</i> project&#8217;s page says:</p>
<blockquote>
<p>Topshelf works with Mono, making it possible to deploy services to Linux. The service installation features are currently Windows only, but others are working on creating native host environment support so that installation and management features are available as well.</p>
</blockquote>
<p style="text-align: left;">So it&#8217;s the next great benefit of <i>Topshelf</i> to use applications built with it on Linux.</p>
<h2 style="text-align: left;">More</h2>
<p style="text-align: left;">If you want to check what&#8217;s more that <i>Topshelf</i> can do, you can visit <a href="http://topshelf-project.com/">project&#8217;s official page</a>, check it&#8217;s <a href="https://github.com/topshelf/topshelf">GitHub repository</a> or watch <a href="https://www.pluralsight.com/courses/topshelf-getting-started-building-windows-services">this very good Pluralsight course</a>.</p>
<h2 style="text-align: left;">Summary</h2>
<p style="text-align: left;">Summing up, I found <i>Topshelf</i> very handy in developing service applications. One of the major pros of using it is ease of installation &#8211; it may become very important in the production environment, especially when dealing with any kind of distributed environment. Moreover, debugging the service as a console application makes fixing bugs quick and comfortable. I recommend everyone to use it in case of a need to write any service application.</p>
<p>The post <a href="https://www.codejourney.net/windows-services-using-topshelf/">Building Windows Services using Topshelf</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/windows-services-using-topshelf/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">26</post-id>	</item>
	</channel>
</rss>
