<?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>C# Archives - CodeJourney.net</title>
	<atom:link href="https://www.codejourney.net/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codejourney.net/tag/c/</link>
	<description>Pragmatic full stack software development</description>
	<lastBuildDate>Thu, 03 Oct 2024 13:41:05 +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>C# Archives - CodeJourney.net</title>
	<link>https://www.codejourney.net/tag/c/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">123174533</site>	<item>
		<title>What is Mutation Testing and Why Should You Use It?</title>
		<link>https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/</link>
					<comments>https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 01 Oct 2024 18:22:58 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mutation testing]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[unit tests]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4825</guid>

					<description><![CDATA[<p>Do you know what is a better testing metric than code coverage? Does 100% code coverage mean your code is well-tested? How to generate unit test cases for free, without using AI? The answer to all these questions is mutation testing. Interested? Read on 😉 Code Coverage &#8211; Our Old Friend You probably know what&#8230;</p>
<p>The post <a href="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/">What is Mutation Testing and Why Should You Use It?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Do you know what is a better testing metric than code coverage? Does 100% code coverage mean your code is well-tested? How to generate unit test cases for free, without using AI?</p>



<p>The answer to all these questions is <strong>mutation testing</strong>. Interested? Read on <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>



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



<h2 class="wp-block-heading">Code Coverage &#8211; Our Old Friend</h2>



<p>You probably know what <a href="https://en.wikipedia.org/wiki/Code_coverage">code coverage</a> is. Traditionally, many teams tend to measure how good their tests&#8217; suite is by percentage line / statements / functions coverage. Some even require this metric to be 100%. Let&#8217;s start with this well-known approach first.</p>



<p>We are working with <code>TicketsPriceCalculator</code> class today. It contains some simple business logic:</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="gist133062269" 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-ticketspricecalculator-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="ticketsPriceCalculator.ts content, created by dsibinski on 04:08PM on October 01, 2024."
    >

        
<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="ticketsPriceCalculator.ts">
        <tr>
          <td id="file-ticketspricecalculator-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-ticketspricecalculator-ts-LC1" class="blob-code blob-code-inner js-file-line">export class TicketsPriceCalculator {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-ticketspricecalculator-ts-LC2" class="blob-code blob-code-inner js-file-line">  calculateTotalTicketsPrice(tickets: Ticket[]): number {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-ticketspricecalculator-ts-LC3" class="blob-code blob-code-inner js-file-line">    if (tickets.length === 0) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-ticketspricecalculator-ts-LC4" class="blob-code blob-code-inner js-file-line">      return 0;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-ticketspricecalculator-ts-LC5" class="blob-code blob-code-inner js-file-line">    }</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-ticketspricecalculator-ts-LC6" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-ticketspricecalculator-ts-LC7" class="blob-code blob-code-inner js-file-line">    let totalPrice = tickets.reduce((sum, ticket) =&gt; sum + ticket.price, 0);</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-ticketspricecalculator-ts-LC8" class="blob-code blob-code-inner js-file-line">    const businessClassTickets = tickets.filter(</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-ticketspricecalculator-ts-LC9" class="blob-code blob-code-inner js-file-line">      (ticket) =&gt; ticket.isBusinessClass</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-ticketspricecalculator-ts-LC10" class="blob-code blob-code-inner js-file-line">    ).length;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-ticketspricecalculator-ts-LC11" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-ticketspricecalculator-ts-LC12" class="blob-code blob-code-inner js-file-line">    let totalDiscountToApply = 0;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-ticketspricecalculator-ts-LC13" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-ticketspricecalculator-ts-LC14" class="blob-code blob-code-inner js-file-line">    // Apply discounts based on total price</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-ticketspricecalculator-ts-LC15" class="blob-code blob-code-inner js-file-line">    if (totalPrice &gt; 2000) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-ticketspricecalculator-ts-LC16" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.25;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-ticketspricecalculator-ts-LC17" class="blob-code blob-code-inner js-file-line">    } else if (totalPrice &gt; 1000 &amp;&amp; totalPrice &lt;= 2000) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-ticketspricecalculator-ts-LC18" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.2;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-ticketspricecalculator-ts-LC19" class="blob-code blob-code-inner js-file-line">    } else if (totalPrice &gt; 500 &amp;&amp; totalPrice &lt;= 1000) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-ticketspricecalculator-ts-LC20" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.15;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-ticketspricecalculator-ts-LC21" class="blob-code blob-code-inner js-file-line">    } else if (totalPrice &gt;= 200 &amp;&amp; totalPrice &lt;= 500) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
          <td id="file-ticketspricecalculator-ts-LC22" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.1;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
          <td id="file-ticketspricecalculator-ts-LC23" class="blob-code blob-code-inner js-file-line">    }</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
          <td id="file-ticketspricecalculator-ts-LC24" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
          <td id="file-ticketspricecalculator-ts-LC25" class="blob-code blob-code-inner js-file-line">    // Apply additional discount based on number of tickets</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
          <td id="file-ticketspricecalculator-ts-LC26" class="blob-code blob-code-inner js-file-line">    if (tickets.length &gt;= 10) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
          <td id="file-ticketspricecalculator-ts-LC27" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.05;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
          <td id="file-ticketspricecalculator-ts-LC28" class="blob-code blob-code-inner js-file-line">    }</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
          <td id="file-ticketspricecalculator-ts-LC29" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
          <td id="file-ticketspricecalculator-ts-LC30" class="blob-code blob-code-inner js-file-line">    // Apply business class discounts</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
          <td id="file-ticketspricecalculator-ts-LC31" class="blob-code blob-code-inner js-file-line">    if (businessClassTickets &gt;= 10) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
          <td id="file-ticketspricecalculator-ts-LC32" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.2;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
          <td id="file-ticketspricecalculator-ts-LC33" class="blob-code blob-code-inner js-file-line">    } else if (businessClassTickets &gt;= 5) {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
          <td id="file-ticketspricecalculator-ts-LC34" class="blob-code blob-code-inner js-file-line">      totalDiscountToApply += 0.1;</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
          <td id="file-ticketspricecalculator-ts-LC35" class="blob-code blob-code-inner js-file-line">    }</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
          <td id="file-ticketspricecalculator-ts-LC36" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
          <td id="file-ticketspricecalculator-ts-LC37" class="blob-code blob-code-inner js-file-line">    return totalPrice * (1 &#8211; totalDiscountToApply);</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L38" class="blob-num js-line-number js-blob-rnum" data-line-number="38"></td>
          <td id="file-ticketspricecalculator-ts-LC38" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator-ts-L39" class="blob-num js-line-number js-blob-rnum" data-line-number="39"></td>
          <td id="file-ticketspricecalculator-ts-LC39" 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/28087f239e57c7dab06d3df2e7532e6d/raw/d388fec49bd951d520a8d0af93c07907c122ce27/ticketsPriceCalculator.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/28087f239e57c7dab06d3df2e7532e6d#file-ticketspricecalculator-ts" class="Link--inTextBlock">
          ticketsPriceCalculator.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>As you can see, the class has one function whith returns the total price to be paid for a set of tickets. On the way, it applies various discounts based on some business rules. Fair enough.</p>



<p>It&#8217;s a critical piece of business logic for the app we&#8217;re working on, but it has never had any tests. We were asked to write unit tests for this class. Our manager strictly requires the code coverage to be 100%. Let&#8217;s do it then. We will go line by line, analyze the business logic and add the tests. Below, you can see the results of running those tests (you can find the tests code <a href="https://gist.github.com/dsibinski/cfc8d36cf7fe45bb9114b950fa898766">here</a>):</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="839" height="427" data-attachment-id="4840" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/1-unit-tests-initial/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/1-unit-tests-initial.jpg?fit=839%2C427&amp;ssl=1" data-orig-size="839,427" 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-unit-tests-initial" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/1-unit-tests-initial.jpg?fit=839%2C427&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/1-unit-tests-initial.jpg?resize=839%2C427&#038;ssl=1" alt="Unit tests before using mutation testing. We have 8 unit tests, all passing. Our code coverage (line, functions, statements, branches) is 100%" class="wp-image-4840" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/1-unit-tests-initial.jpg?w=839&amp;ssl=1 839w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/1-unit-tests-initial.jpg?resize=768%2C391&amp;ssl=1 768w" sizes="(max-width: 839px) 100vw, 839px" /></figure>



<p></p>



<p>Wow, that&#8217;s awesome! We did a great job. We have <strong>8 unit tests which provide 100% statements, branch, functions and lines coverage</strong>!</p>



<p>So now we are really safe, aren&#8217;t we? <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>Yeah&#8230; until you know what mutation testing is <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>



<h2 class="wp-block-heading">What Is Mutation Testing?</h2>



<p>The idea of mutation testing is to <em>mutate</em> (change) our code. Mutation testing tools introduce changes into our production code. These changes can be really anything &#8211; from reverting a condition of an <code>if</code> statement, to changing some operators or changing a <code>string</code> value. For instance, here are some logical mutations <a href="https://stryker-mutator.io/">Stryker Mutator</a> is able to introduce (you can find the list of all mutations supported by Stryker <a href="https://stryker-mutator.io/docs/mutation-testing-elements/supported-mutators/">here</a>):</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" decoding="async" width="445" height="320" data-attachment-id="4845" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/2-stryker-logical-mutations/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/2-stryker-logical-mutations.jpg?fit=445%2C320&amp;ssl=1" data-orig-size="445,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="2-stryker-logical-mutations" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/2-stryker-logical-mutations.jpg?fit=445%2C320&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/2-stryker-logical-mutations.jpg?resize=445%2C320&#038;ssl=1" alt="Logical operator mutations supported by Stryker Mutator" class="wp-image-4845"/></figure>
</div>


<p></p>



<p>In effect, they generate modified versions of our code, which are called <em>mutants</em>. Makes sense <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>Each mutant contains a single modification in our source code. What happens next is crucial. Mutation testing tool takes this mutant (it is used as the code under tests now) and executes all of our unit tests against it. The result may be twofold:</p>



<ul class="wp-block-list">
<li>all tests have passed. In other words, the <em>mutant has</em> <em>survived</em>. <strong>This is a bad situation</strong>. It implies that the modification of our source code was not detected by our tests</li>



<li>at least one test has failed. In other words, the <em>mutant has been killed</em>. <strong>This is a good scenario</strong>. It means that our tests detect changes in the production code and efficiently cover this particular scenario.</li>
</ul>



<p>The flow is more or less like this <a href="https://peterevans.dev/posts/mutation-testing/">schema from Peter Evans&#8217; blog</a> presents:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" decoding="async" width="353" height="580" data-attachment-id="4847" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/3-mutation-test-schema/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/3-mutation-test-schema.png?fit=353%2C580&amp;ssl=1" data-orig-size="353,580" 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-mutation-test-schema" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/3-mutation-test-schema.png?fit=353%2C580&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/3-mutation-test-schema.png?resize=353%2C580&#038;ssl=1" alt="Schema of mutation testing" class="wp-image-4847" style="width:353px;height:auto"/></figure>
</div>


<p></p>



<p>But why would anyone change the production code on purpose by introducing some stupid changes? It may seem counterintuitive for now, but let&#8217;s see how we can use it to our leverage.</p>



<h2 class="wp-block-heading">Mutation Testing with Stryker Mutator</h2>



<p>Let&#8217;s clearly state what we are starting with:</p>



<p><strong>8 unit tests, 100% code coverage</strong></p>



<p>Let&#8217;s now run mutation testing on our code. We are using TypeScript here, so let&#8217;s go with <a href="https://stryker-mutator.io/">Stryker Mutator</a>.</p>



<p>Here&#8217;s the result of running Stryker with <code>npx stryker run</code> on our code:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="958" height="163" data-attachment-id="4854" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/4-stryker-mutator-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/4-stryker-mutator-1.jpg?fit=958%2C163&amp;ssl=1" data-orig-size="958,163" 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-stryker-mutator-1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/4-stryker-mutator-1.jpg?fit=958%2C163&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/4-stryker-mutator-1.jpg?resize=958%2C163&#038;ssl=1" alt="Mutation test result - first run. Mutation score 78%, survived mutants 15" class="wp-image-4854" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/4-stryker-mutator-1.jpg?w=958&amp;ssl=1 958w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/4-stryker-mutator-1.jpg?resize=768%2C131&amp;ssl=1 768w" sizes="auto, (max-width: 958px) 100vw, 958px" /></figure>
</div>


<p></p>



<p>As you can see, 53 mutants were killed, but 15 of them survived. This gives us a mutation score of 78%. Let&#8217;s call it <em>mutation coverage</em> from now on. So to make it clear, this is our starting situation:</p>



<p><strong>8 unit tests, 100% code coverage, 78% mutation coverage</strong></p>



<p>Let&#8217;s now see how to kill those remaining mutants.</p>



<h2 class="wp-block-heading">Killing First Mutants</h2>



<p>In order to kill the mutants and improve our mutation score, we need to write more unit tests. Sounds logical, doesn&#8217;t it?</p>



<p>If still not, let&#8217;s take a deeper look at mutation tests results in VS Code. Stryker lists details of every survived mutant, for example this one:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="864" height="198" data-attachment-id="4855" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/5-stryker-mutant-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/5-stryker-mutant-1.jpg?fit=864%2C198&amp;ssl=1" data-orig-size="864,198" 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-stryker-mutant-1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/5-stryker-mutant-1.jpg?fit=864%2C198&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/5-stryker-mutant-1.jpg?resize=864%2C198&#038;ssl=1" alt="First mutant generated by Stryker" class="wp-image-4855" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/5-stryker-mutant-1.jpg?w=864&amp;ssl=1 864w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/5-stryker-mutant-1.jpg?resize=768%2C176&amp;ssl=1 768w" sizes="auto, (max-width: 864px) 100vw, 864px" /></figure>
</div>


<p></p>



<p>Stryker changed the greater or equal (<code>>=</code>) operator to greater operator (<code>></code>). This is a very common and very useful mutation. It usually means that our tests don&#8217;t cover the edge case associated with this particular condition.</p>



<p>In this case, the edge case value seems to be <code>5</code>. More precisely, what happens if the number of business class tickets is <em>exactly 5</em>? We don&#8217;t know, because there is no test for this particular edge case!</p>



<p>Let&#8217;s add it:</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="gist133063837" 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-ticketspricecalculator_edgecase-test-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="ticketsPriceCalculator_edgeCase.test.ts content, created by dsibinski on 05:23PM on October 01, 2024."
    >

        
<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="ticketsPriceCalculator_edgeCase.test.ts">
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC1" class="blob-code blob-code-inner js-file-line">  test(&quot;should apply 10% discount if there are exactly 5 business class tickets&quot;, () =&gt; {</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC2" class="blob-code blob-code-inner js-file-line">    const tickets = Array.from({ length: 5 }, () =&gt; ({</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC3" class="blob-code blob-code-inner js-file-line">      price: 10,</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC4" class="blob-code blob-code-inner js-file-line">      isBusinessClass: true,</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC5" class="blob-code blob-code-inner js-file-line">    }));</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC6" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC7" class="blob-code blob-code-inner js-file-line">    const totalPrice = calculator.calculateTotalTicketsPrice(tickets);</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-ticketspricecalculator_edgecase-test-ts-LC8" class="blob-code blob-code-inner js-file-line">    expect(totalPrice).toBe(45); // 10% discount</td>
        </tr>
        <tr>
          <td id="file-ticketspricecalculator_edgecase-test-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-ticketspricecalculator_edgecase-test-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/ee04a5c91df633a66935ed6a663f3ae1/raw/836811b2f5ba7f306346a9c11f4fe7de42ce2b89/ticketsPriceCalculator_edgeCase.test.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/ee04a5c91df633a66935ed6a663f3ae1#file-ticketspricecalculator_edgecase-test-ts" class="Link--inTextBlock">
          ticketsPriceCalculator_edgeCase.test.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>The test passes. Let&#8217;s run mutation tests again:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="961" height="166" data-attachment-id="4856" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/6-stryker-mutator-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/6-stryker-mutator-2.jpg?fit=961%2C166&amp;ssl=1" data-orig-size="961,166" 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-stryker-mutator-2" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/6-stryker-mutator-2.jpg?fit=961%2C166&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/6-stryker-mutator-2.jpg?resize=961%2C166&#038;ssl=1" alt="Struker Mutator second run - already 14 mutants survived and almost 80% mutation coverage" class="wp-image-4856" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/6-stryker-mutator-2.jpg?w=961&amp;ssl=1 961w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/6-stryker-mutator-2.jpg?resize=768%2C133&amp;ssl=1 768w" sizes="auto, (max-width: 961px) 100vw, 961px" /></figure>
</div>


<p></p>



<p>That&#8217;s it! We have a new unit test and 1 more mutant killed <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" />  Current state:</p>



<p><strong>9 (+1) unit tests, 100% code coverage, 79% mutation coverage</strong></p>



<p>I think you&#8217;re now getting what this is all about. We should be adding unit tests to cover the edge cases detected by mutations until all (or most) mutants are killed.</p>



<h2 class="wp-block-heading">Mutation Testing &#8211; Free Unit Tests Generator</h2>



<p>After adding 1 more test, the results look as follows:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="960" height="164" data-attachment-id="4859" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/7-stryker-mutator-3/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/7-stryker-mutator-3.jpg?fit=960%2C164&amp;ssl=1" data-orig-size="960,164" 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-stryker-mutator-3" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/7-stryker-mutator-3.jpg?fit=960%2C164&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/7-stryker-mutator-3.jpg?resize=960%2C164&#038;ssl=1" alt="Struker mutator with 10 tests - 86% mutation coverage" class="wp-image-4859" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/7-stryker-mutator-3.jpg?w=960&amp;ssl=1 960w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/7-stryker-mutator-3.jpg?resize=768%2C131&amp;ssl=1 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>
</div>


<p></p>



<p><strong>10 (+2) unit tests, 100% code coverage, 86% mutation coverage</strong></p>



<p>Finally, this is what we managed to get after a few minutes of work:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="959" height="165" data-attachment-id="4860" data-permalink="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/8-stryker-mutator-4/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/8-stryker-mutator-4.jpg?fit=959%2C165&amp;ssl=1" data-orig-size="959,165" 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="8-stryker-mutator-4" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/8-stryker-mutator-4.jpg?fit=959%2C165&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/8-stryker-mutator-4.jpg?resize=959%2C165&#038;ssl=1" alt="" class="wp-image-4860" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/8-stryker-mutator-4.jpg?w=959&amp;ssl=1 959w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2024/10/8-stryker-mutator-4.jpg?resize=768%2C132&amp;ssl=1 768w" sizes="auto, (max-width: 959px) 100vw, 959px" /></figure>
</div>


<p></p>



<p>And we now have 17 unit tests in our suite! The final score looks like that:</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f38a.png" alt="🎊" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>17 (+9) unit tests, 100% code coverage, 96% mutation coverage</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f38a.png" alt="🎊" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>Notice what happened here. <strong>We started with 8 unit tests and finished with 17! This is awesome! That&#8217;s how mutation testing is a free unit tests generator</strong>. And you don&#8217;t even need AI for that <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>What&#8217;s more, the generated mutations even forced me to make a little tweak to the production code. It exposed some things that didn&#8217;t make sense. I could make this change to the production code, because my tests&#8217; suite was already quite substantial.</p>



<p>Note that I didn&#8217;t push to gain 100% mutation coverage. The 3 mutants that survived don&#8217;t make much sense in our case. I encourage you to <a href="https://github.com/dsibinski/codejourney/tree/main/mutation-testing">get the code</a> and execute <code>npx stryker run</code> in the application folder to see for yourself <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 percentage value doesn&#8217;t matter in that case. What matters is that we got 9 new unit tests and our tests&#8217; suite is more robust. Now we can go and tell our manager that the business-critical code is well tested <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60a.png" alt="😊" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">So What Now?</h2>



<p>I hope you see how valuable mutation testing is. It&#8217;s not a perfect tool that suits all cases. For example, it&#8217;s not easy to use mutation testing for complex legacy code. However, if your logic is nicely isolated, it could be a great tool. Especially if your production code heavily depends on calculations and many conditions. You may be surprised how many edge cases mutation testing can find.</p>



<p>I also love using mutation testing with TDD. These two techniques nicely complement each other.</p>



<p>I encourage you to go and try mutation testing. There are different mutation tools for various programming languages:</p>



<ul class="wp-block-list">
<li>C#, JavaScript, TypeScript, Scala: <a href="https://stryker-mutator.io/">Stryker Mutator</a></li>



<li>Ruby: <a href="https://github.com/mbj/mutant">mutant</a></li>



<li>Java: <a href="https://pitest.org/">pitest</a></li>



<li>PHP: <a href="https://infection.github.io/">Infection</a></li>



<li>C++: <a href="https://github.com/nlohmann/mutate_cpp">Mutate++</a></li>
</ul>



<p>&#8230;and probably many more. Just do some research for the language you work with and give it a try <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;" /> Because <a href="https://www.codejourney.net/improve-your-tests-with-assert-object-pattern/">testing</a> is cool, isn&#8217;t 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>



<p>You can find the full source code used in this article <a href="https://github.com/dsibinski/codejourney/tree/main/mutation-testing">here</a>.</p>
<p>The post <a href="https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/">What is Mutation Testing and Why Should You Use It?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/what-is-mutation-testing-and-why-you-should-use-it/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4825</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"><span class=pl-k>public</span> <span class=pl-smi>List</span><span class=pl-c1>&lt;</span><span class=pl-smi>UserViewModel</span><span class=pl-c1>&gt;</span> <span class=pl-en>AllUsers</span><span class=pl-kos>(</span><span class=pl-kos>)</span></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"><span class=pl-kos>{</span></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">    <span class=pl-k>var</span> <span class=pl-s1>usersViewModels</span> <span class=pl-c1>=</span> <span class=pl-s1>TestDataGenerator</span><span class=pl-kos>.</span><span class=pl-en>GetTestUsers</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">    <span class=pl-k>return</span> <span class=pl-s1>usersViewModels</span><span class=pl-kos>.</span><span class=pl-en>OrderBy</span><span class=pl-kos>(</span>uvm <span class=pl-c1>=&gt;</span> <span class=pl-s1>uvm</span><span class=pl-kos>.</span><span class=pl-s1>Name</span><span class=pl-kos>)</span><span class=pl-kos>.</span><span class=pl-en>ToList</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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"><span class=pl-kos>}</span></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"><span class=pl-k>public</span> <span class=pl-k>record</span> <span class=pl-smi>UserViewModel</span><span class=pl-kos>(</span><span class=pl-smi>Guid</span> <span class=pl-s1>Id</span><span class=pl-kos>,</span> <span class=pl-smi>string</span> <span class=pl-s1>Name</span><span class=pl-kos>,</span> <span class=pl-smi>string</span> <span class=pl-s1>LastName</span><span class=pl-kos>,</span> </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">    <span class=pl-smi>string</span> <span class=pl-s1>Login</span><span class=pl-kos>,</span> <span class=pl-smi>bool</span> <span class=pl-s1>IsActive</span><span class=pl-kos>,</span> <span class=pl-smi>int</span> <span class=pl-s1>LoyaltyPoints</span><span class=pl-kos>,</span> <span class=pl-smi>AddressViewModel</span><span class=pl-c1>?</span> <span class=pl-s1>Address</span> <span class=pl-c1>=</span> <span class=pl-c1>null</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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"><span class=pl-k>export</span> <span class=pl-k>interface</span> <span class=pl-smi>UserViewModel</span> <span class=pl-kos>{</span></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">  <span class=pl-c1>id</span>: <span class=pl-smi>Guid</span><span class=pl-kos>;</span></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">  <span class=pl-c1>name</span>: <span class=pl-smi>string</span><span class=pl-kos>;</span></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">  <span class=pl-c1>lastName</span>: <span class=pl-smi>string</span><span class=pl-kos>;</span></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">  <span class=pl-c1>login</span>: <span class=pl-smi>string</span><span class=pl-kos>;</span></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">  <span class=pl-c1>isActive</span>: <span class=pl-smi>boolean</span><span class=pl-kos>;</span></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">  <span class=pl-c1>loyaltyPoints</span>: <span class=pl-smi>number</span><span class=pl-kos>;</span></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">  <span class=pl-c1>address</span>: <span class=pl-smi>AddressViewModel</span> <span class=pl-c1>|</span> <span class=pl-c1>null</span><span class=pl-kos>;</span></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"><span class=pl-kos>}</span></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" loading="lazy" 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="auto, (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" loading="lazy" 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="auto, (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"><span class=pl-k>public</span> <span class=pl-k>record</span> <span class=pl-smi>UserViewModel</span><span class=pl-kos>(</span><span class=pl-smi>Guid</span> <span class=pl-s1>Id</span><span class=pl-kos>,</span> <span class=pl-smi>string</span> <span class=pl-s1>Name</span><span class=pl-kos>,</span> <span class=pl-smi>string</span> <span class=pl-s1>LastName</span><span class=pl-kos>,</span> </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">    <span class=pl-smi>string</span> <span class=pl-s1>Login</span><span class=pl-kos>,</span> <span class=pl-smi>bool</span> <span class=pl-s1>IsActive</span><span class=pl-kos>,</span> <span class=pl-smi>int</span> <span class=pl-s1>FidelityPoints</span><span class=pl-kos>,</span> <span class=pl-smi>AddressViewModel</span><span class=pl-c1>?</span> <span class=pl-s1>Address</span> <span class=pl-c1>=</span> <span class=pl-c1>null</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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" loading="lazy" 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="auto, (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">
https://gist.github.com/dsibinski/9c7759dff996babccf1b14da276d76c8
</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>Write Test Progress To The Console With NUnit</title>
		<link>https://www.codejourney.net/write-test-progress-to-the-console-with-nunit/</link>
					<comments>https://www.codejourney.net/write-test-progress-to-the-console-with-nunit/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 19 Jun 2022 13:07:28 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4070</guid>

					<description><![CDATA[<p>I recently needed to write test progress to the console with NUnit. The task we want to solve here is basically the TODO part of this snippet: The title picture of this article shows the end result. If you want to know the solution, keep reading 🙂 Context The context of this need is very&#8230;</p>
<p>The post <a href="https://www.codejourney.net/write-test-progress-to-the-console-with-nunit/">Write Test Progress To The Console With NUnit</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I recently needed to write test progress to the console with NUnit. The task we want to solve here is basically the <em>TODO</em> part of this snippet:</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="gist116902181" 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-nunit_test_progress_todo-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="NUnit_test_progress_todo.cs content, created by dsibinski on 04:54AM on June 19, 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="NUnit_test_progress_todo.cs">
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-nunit_test_progress_todo-cs-LC1" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>[</span><span class=pl-c1>TestFixture</span><span class=pl-kos>]</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-nunit_test_progress_todo-cs-LC2" class="blob-code blob-code-inner js-file-line"><span class=pl-k>public</span> <span class=pl-k>class</span> <span class=pl-smi>MyTests</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-nunit_test_progress_todo-cs-LC3" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-nunit_test_progress_todo-cs-LC4" class="blob-code blob-code-inner js-file-line">    <span class=pl-kos>[</span><span class=pl-c1>Test</span><span class=pl-kos>]</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-nunit_test_progress_todo-cs-LC5" class="blob-code blob-code-inner js-file-line">    <span class=pl-k>public</span> <span class=pl-smi>void</span> <span class=pl-en>SampleTest</span><span class=pl-kos>(</span><span class=pl-kos>)</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-nunit_test_progress_todo-cs-LC6" class="blob-code blob-code-inner js-file-line">    <span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-nunit_test_progress_todo-cs-LC7" class="blob-code blob-code-inner js-file-line">        <span class=pl-c>// some operations here, like starting a server for tests in-memory&#8230;</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-nunit_test_progress_todo-cs-LC8" class="blob-code blob-code-inner js-file-line">        </td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-nunit_test_progress_todo-cs-LC9" class="blob-code blob-code-inner js-file-line">        <span class=pl-c>// TODO: inform the &#39;user&#39; (the one who runs the test) that the server is already running</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-nunit_test_progress_todo-cs-LC10" class="blob-code blob-code-inner js-file-line">        <span class=pl-k>while</span> <span class=pl-kos>(</span><span class=pl-c1>true</span><span class=pl-kos>)</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-nunit_test_progress_todo-cs-LC11" class="blob-code blob-code-inner js-file-line">        <span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-nunit_test_progress_todo-cs-LC12" class="blob-code blob-code-inner js-file-line">            <span class=pl-c>// keep it running on purpose (e.g. for E2E tests)</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-nunit_test_progress_todo-cs-LC13" class="blob-code blob-code-inner js-file-line">        <span class=pl-kos>}</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-nunit_test_progress_todo-cs-LC14" class="blob-code blob-code-inner js-file-line">        </td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-nunit_test_progress_todo-cs-LC15" class="blob-code blob-code-inner js-file-line">    <span class=pl-kos>}</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress_todo-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-nunit_test_progress_todo-cs-LC16" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>}</span></td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

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

</div></figure>



<p>The title picture of this article shows the end result. If you want to know the solution, keep 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-4070"></span>



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



<p>The context of this need is very simple. I have a unit test in which I want to perform some operations and keep the test running indefinitely afterwards. The use case might be instantiation of an <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.testhost.testserver?view=aspnetcore-6.0">in-memory test server</a>. After that, I want to inform the user (programmer or the one running the test) that the server is up and running. I want to do that <strong>before the test finishes</strong>. In other words: <strong>I want to write the test&#8217;s output while it&#8217;s still running</strong>. </p>



<p>In my case, I was running two .NET Core apps in-memory. The backend server app and the ASP.NET Core web application. In the process, the web app got its IP address assigned dynamically. Meaning that the IP was different with each test run. This particular test was used to run the app in-memory and let the user manually use the application. It means the user must know the IP/URL of the in-memory web app. That&#8217;s why I needed to output the dynamic IP address into the NUnit test output <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 class="wp-block-heading">Solution</h2>



<p>The solution to write test progress to the console with NUnit is very simple. To do that, use <code>TestContext.Progress.WriteLine(string)</code> method from <code>NUnit.Framework</code> namespace:</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="gist116902272" 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-nunit_test_progress-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="NUnit_test_progress.cs content, created by dsibinski on 05:05AM on June 19, 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="NUnit_test_progress.cs">
        <tr>
          <td id="file-nunit_test_progress-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-nunit_test_progress-cs-LC1" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>[</span><span class=pl-c1>TestFixture</span><span class=pl-kos>]</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-nunit_test_progress-cs-LC2" class="blob-code blob-code-inner js-file-line"><span class=pl-k>public</span> <span class=pl-k>class</span> <span class=pl-smi>MyTests</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-nunit_test_progress-cs-LC3" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-nunit_test_progress-cs-LC4" class="blob-code blob-code-inner js-file-line">    <span class=pl-kos>[</span><span class=pl-c1>Test</span><span class=pl-kos>]</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-nunit_test_progress-cs-LC5" class="blob-code blob-code-inner js-file-line">    <span class=pl-k>public</span> <span class=pl-smi>void</span> <span class=pl-en>SampleTest</span><span class=pl-kos>(</span><span class=pl-kos>)</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-nunit_test_progress-cs-LC6" class="blob-code blob-code-inner js-file-line">    <span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-nunit_test_progress-cs-LC7" class="blob-code blob-code-inner js-file-line">        <span class=pl-c>// some operations here, like starting a server for tests in-memory&#8230;</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-nunit_test_progress-cs-LC8" class="blob-code blob-code-inner js-file-line">        </td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-nunit_test_progress-cs-LC9" class="blob-code blob-code-inner js-file-line">        <span class=pl-s1>TestContext</span><span class=pl-kos>.</span><span class=pl-s1>Progress</span><span class=pl-kos>.</span><span class=pl-en>WriteLine</span><span class=pl-kos>(</span><span class=pl-s>&quot;The server is running now! You can reach it on https://localhost:8067/&quot;</span><span class=pl-kos>)</span><span class=pl-kos>;</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-nunit_test_progress-cs-LC10" class="blob-code blob-code-inner js-file-line">        <span class=pl-k>while</span> <span class=pl-kos>(</span><span class=pl-c1>true</span><span class=pl-kos>)</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-nunit_test_progress-cs-LC11" class="blob-code blob-code-inner js-file-line">        <span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-nunit_test_progress-cs-LC12" class="blob-code blob-code-inner js-file-line">            <span class=pl-c>// keep it running on purpose (e.g. for E2E tests)</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-nunit_test_progress-cs-LC13" class="blob-code blob-code-inner js-file-line">        <span class=pl-kos>}</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-nunit_test_progress-cs-LC14" class="blob-code blob-code-inner js-file-line">        </td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-nunit_test_progress-cs-LC15" class="blob-code blob-code-inner js-file-line">    <span class=pl-kos>}</span></td>
        </tr>
        <tr>
          <td id="file-nunit_test_progress-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-nunit_test_progress-cs-LC16" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>}</span></td>
        </tr>
  </table>
</div>


    </div>

  </div>

</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/03221c21614c48cef6fdbbd5e11accb4/raw/1880d0e1f47cb145c600d96e5f1d392bf5728028/NUnit_test_progress.cs" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/03221c21614c48cef6fdbbd5e11accb4#file-nunit_test_progress-cs" class="Link--inTextBlock">
          NUnit_test_progress.cs
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>And that&#8217;s it! I&#8217;m publishing this simple solution, because it took me some time to find <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 previously tried with <code>TestContext.Out.WriteLine</code>, <code>System.Diagnostics.Trace.WriteLine</code> and <code>System.Console.WriteLine</code>, but all of them output the text <em>after </em>the test finishes.</p>



<p>Finally, you can also run the test from cmd using <code>dotnet test</code>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="189" data-attachment-id="4081" data-permalink="https://www.codejourney.net/write-test-progress-to-the-console-with-nunit/nunit_cmd_console_progress/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?fit=1119%2C206&amp;ssl=1" data-orig-size="1119,206" 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="NUnit_cmd_console_progress" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?fit=1024%2C189&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?resize=1024%2C189&#038;ssl=1" alt="" class="wp-image-4081" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?resize=1024%2C189&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?resize=300%2C55&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?resize=768%2C141&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?w=1119&amp;ssl=1 1119w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Hope it&#8217;s useful!</p>
<p>The post <a href="https://www.codejourney.net/write-test-progress-to-the-console-with-nunit/">Write Test Progress To The Console With NUnit</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/write-test-progress-to-the-console-with-nunit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4070</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>Is It Worth Migrating to TypeScript?</title>
		<link>https://www.codejourney.net/is-it-worth-migrating-to-typescript/</link>
					<comments>https://www.codejourney.net/is-it-worth-migrating-to-typescript/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 29 Aug 2020 11:03:05 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ts]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[typescript migration]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3840</guid>

					<description><![CDATA[<p>Choosing migration strategy Bright side of migrating to TypeScript If you are a JavaScript developer, the best advice I can give you is to start using TypeScript 🙂 In this section I&#8217;m describing what positively surprised me since the beginning of starting to use TypeScript. Types &#8220;for free&#8221; As soon as we changed our transpiler&#8230;</p>
<p>The post <a href="https://www.codejourney.net/is-it-worth-migrating-to-typescript/">Is It Worth Migrating to TypeScript?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>For the past year I&#8217;ve been working on a JavaScript project for my client. We have a mid-size web application. We use React as the web development framework. Few months ago we decided to start migrating to TypeScript.</p>
<p>Today I can say that <strong>it was the best decision we could make</strong>. TypeScript makes working with JavaScript, which is sometimes <a href="https://www.codejourney.net/2018/11/10-most-shocking-javascript-features-for-csharp-developers/" target="_blank" rel="noopener noreferrer">surprising and quite hard to understand</a>, so much better experience. However, there were some challenges on this journey. If you want to know what issues we met and how we solved them, but also what huge advantages TypeScript gave us &#8211; read on <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><em>I will not discuss TypeScript itself in this article. This is a pure recap of challenges and the experience I gained when migrating to TypeScript.</em></p>



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



<h2 class="wp-block-heading">Choosing migration strategy</h2>



<p>Before starting migrating to TypeScript, we had to choose the best strategy for this process. There were two possibilities we considered: <strong>migrating the whole JavaScript codebase to TypeScript at once</strong> or <strong>switching to TypeScript compiler and migrating part-by-part</strong>.</p>
<p>For those who are not familiar with TypeScript &#8211; it is a superset of JavaScript which adds typing information to your JS code. It means that <strong>every JavaScript code is also a valid TypeScript code</strong>. When compiling TypeScript code, TS compiler removes the typing data and outputs readable, vanilla JavaScript code ready to be executed.</p>
<p>Migrating the whole codebase to TypeScript would mean to change all files extensions to TypeScript ones: <em>.js</em> to <em>.ts</em> and <em>.jsx</em> to <em>.tsx</em>. It would also mean that TypeScript compiler starts checking types in those files. This approach is doable, but &#8211; depending on the size of your project &#8211; can take a long time. During migration the code would be frozen until you fully migrate the project. Also, for TypeScript beginners, it could be a bit frustrating having to type everything at once or use some tricks to tell TypeScript to ignore checking types in many cases (because the type is not known at this stage, or we want to do it later etc.).</p>
<p>Because of that, <strong>we decided to migrate part-by-part, having JavaScript and TypeScript files at the same time</strong>. It is possible thanks to enabling <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html" target="_blank" rel="noopener noreferrer"><em>allowJs&nbsp;</em>TS compiler option</a>. It means that TypeScript will compile both TS and JS files. Such approach allows the coexistence of old JS code with the new TS parts. It also allows moving only chosen parts of the application to TypeScript at the beginning and come back to the others later.</p>
<p>In our web application the biggest JS files have few thousand lines of code. Some of this legacy code still didn&#8217;t use React, but <a href="https://backbonejs.org/" target="_blank" rel="noopener noreferrer">Backbone</a> as their framework. We didn&#8217;t want to touch these oldest files in the beginning. Instead, <strong>we moved few recently written functionalities to TypeScript straightaway and decided to implement everything new in TS as well</strong>.</p>



<h2 class="wp-block-heading">Bright side of migrating to TypeScript</h2>



<p>If you are a JavaScript developer, the best advice I can give you is to start using TypeScript <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 this section I&#8217;m describing what positively surprised me since the beginning of starting to use TypeScript.</p>



<h3 class="wp-block-heading">Types &#8220;for free&#8221;</h3>



<p>As soon as we changed our transpiler from <em>babel-loader</em> to <em>ts-loader, </em>I wanted to know how we can get typing information for already-installed npm packages. It turns out that <strong>for 98% of the packages we used there&#8217;s already a typing information available</strong> as a separate npm package. </p>



<p>In most cases if you have a npm package called <em>abc</em> there&#8217;s a typing package available called <em>@types/abc</em>. I explored our <em>package.json </em>and for each package listed there I just executed <em>npm install @types/package-name</em>. 2 or 3 older or not-so-popular packages didn&#8217;t have types definitions available, but for the rest we got types for free, without having to type anything ourselves. This was a first, very nice surprise <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 find more information about TypeScript types definition packages, as well as contribute one yourself, <a href="https://github.com/DefinitelyTyped/DefinitelyTyped" target="_blank" rel="noreferrer noopener">here</a>.</p>



<h3 class="wp-block-heading">All new code is typed</h3>



<p>As I wrote before, every new feature we&#8217;ve added since the migration is written in TypeScript. Thanks to that, <strong>all n</strong>ew code we write <strong>is strongly typed</strong>. What&#8217;s remarkable here is that it required almost no effort. We just switched the compiler to TS (with a small struggle with webpack configuration, about which you can read below) and suddenly got into typed world for every new feature we implement. Quite impressive, 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>



<h3 class="wp-block-heading">JS-TS friendship</h3>



<p>Coexistence and friendship between JavaScript and TypeScript is HUGE. <strong>These two creatures are not enemies &#8211; they are best friends</strong> <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;" /> We&#8217;ve already gone through many scenarios when we needed to use something written in TS in a JS file and otherwise. It turns out that all of these scenarios are manageable. Sometimes you need to import something differently (for example using <em>require</em> instead of <em>import</em>), but it&#8217;s all possible. We found it super easy to write new features or even add parts of new features to already-existing JS code, writing everything in TypeScript.</p>



<p>We also rewrote some JS files that were used from multiple places in the app to TypeScript. As an example of JS-TS coexistence, I&#8217;m presenting below the potential <em>.ts</em> source code you might have. It contains both old, legacy JS code when we used <em>module.exports</em> and <em>prototype</em> to expose various services for data fetching, as well as a brand-new, nicely-exported TypeScript class:</p>



<p><style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist105109386" 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-services-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="services.ts content, created by dsibinski on 08:09AM on August 29, 2020."
    >

        
<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="services.ts">
        <tr>
          <td id="file-services-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-services-ts-LC1" class="blob-code blob-code-inner js-file-line">module.exports.UsersService = function (url) {</td>
        </tr>
        <tr>
          <td id="file-services-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-services-ts-LC2" class="blob-code blob-code-inner js-file-line">  // &#8230; UsersService init code &#8230;</td>
        </tr>
        <tr>
          <td id="file-services-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-services-ts-LC3" class="blob-code blob-code-inner js-file-line">};</td>
        </tr>
        <tr>
          <td id="file-services-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-services-ts-LC4" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-services-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-services-ts-LC5" class="blob-code blob-code-inner js-file-line">module.exports.UsersService.prototype.getUser = function (id) {</td>
        </tr>
        <tr>
          <td id="file-services-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-services-ts-LC6" class="blob-code blob-code-inner js-file-line">  // &#8230; code to get active user by id &#8230;</td>
        </tr>
        <tr>
          <td id="file-services-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-services-ts-LC7" class="blob-code blob-code-inner js-file-line">};</td>
        </tr>
        <tr>
          <td id="file-services-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-services-ts-LC8" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-services-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-services-ts-LC9" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-services-ts-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-services-ts-LC10" class="blob-code blob-code-inner js-file-line">export class NewUsersService {</td>
        </tr>
        <tr>
          <td id="file-services-ts-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-services-ts-LC11" class="blob-code blob-code-inner js-file-line">  url: string;</td>
        </tr>
        <tr>
          <td id="file-services-ts-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-services-ts-LC12" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-services-ts-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-services-ts-LC13" class="blob-code blob-code-inner js-file-line">  constructor(url: string) {</td>
        </tr>
        <tr>
          <td id="file-services-ts-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-services-ts-LC14" class="blob-code blob-code-inner js-file-line">    // &#8230; NewUsersService init code &#8230;</td>
        </tr>
        <tr>
          <td id="file-services-ts-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-services-ts-LC15" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-services-ts-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-services-ts-LC16" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-services-ts-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-services-ts-LC17" class="blob-code blob-code-inner js-file-line">  getUser(id: number): JQuery.Promise&lt;UserViewModel, any, any&gt; {</td>
        </tr>
        <tr>
          <td id="file-services-ts-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-services-ts-LC18" class="blob-code blob-code-inner js-file-line">    // &#8230; code to get active user by id &#8230;</td>
        </tr>
        <tr>
          <td id="file-services-ts-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-services-ts-LC19" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-services-ts-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-services-ts-LC20" 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/fceb3650f2121640a5e32a78ec3dc740/raw/504b504a930a8262f334017f8aeddc675e3692bf/services.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/fceb3650f2121640a5e32a78ec3dc740#file-services-ts" class="Link--inTextBlock">
          services.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>
 </p>



<p>Such code can of course be in separate files, but it only shows how good TS and JS can coexist together. You can keep your old code working, while implementing anything new in TypeScript.</p>



<h3 class="wp-block-heading">Flexibility in partial migrating to TypeScript</h3>



<p>It turns out that choosing to partially move our web project to TypeScript was a great decision. The team wouldn&#8217;t be so happy and enthusiastic about TS if we told them to move legacy Backbone code to TypeScript. Instead, we gave them a nice tool which can be used for all new stuff. Also, if someone likes the idea and wants to move already-existing JS file to TS, he or she is welcome to do so. </p>



<p>That&#8217;s how <strong>we are still migrating our project to TypeScript, without any hustle and frustration</strong> <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>



<h3 class="wp-block-heading">Wisdom of TypeScript</h3>



<p>I&#8217;m positively surprised by TypeScript almost every day. At some point I get to the issue that seems hard to be solved or quite non-standard. Then I find a solution online and <strong>it makes me really impressed about the job <a href="https://github.com/microsoft/TypeScript" target="_blank" rel="noreferrer noopener">the community and Microsoft has been doing</a> around the language</strong>. </p>



<p>These are sometimes small, but smart things. Recently we got surprised by <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types" target="_blank" rel="noreferrer noopener">keyof</a>, which lets you get names of the allowed properties of your type. Generally <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html" target="_blank" rel="noreferrer noopener">the typing system</a> is really advanced and impressive. For some it can be a disadvantage, but I think it gives an enormous flexibility. </p>



<p>This is somehow the JavaScript you-can-do-whatever-you-want philosophy smuggled into TypeScript <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;" /> But in a much smarter way. I&#8217;m sure that when you start working with TypeScript you&#8217;ll get what I mean by its wisdom <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>



<h3 class="wp-block-heading">Small effort, huge benefits</h3>



<p>Last, but not least, I must admit that <strong>migrating to TypeScript was quite an easy and smooth process. The value for the effort is huge</strong>. You get a typed world with very little work.</p>



<h2 class="wp-block-heading">Migrating to TypeScript struggles</h2>



<p>During the migration process we met few difficulties. Some of them we managed to solve fully or partially. If you have any better ideas on these things, feel free to let me know in the comments.</p>



<h3 class="wp-block-heading">Complexity of webpack configuration</h3>



<p>When switching to TypeScript we had few issues with <a href="https://webpack.js.org/" target="_blank" rel="noreferrer noopener">webpack</a> configuration. We have used <a href="https://github.com/babel/babel-loader" target="_blank" rel="noreferrer noopener"><em>babel-loader</em></a> before for transpiling JavaScript and initially we wanted to keep it in the TS compilation process. We first tried to keep <em>babel-loader</em> for JS(X) files and use <em>ts-loader</em> for TS(X) files, but it didn&#8217;t work &#8211; we were getting weird compilation errors. </p>



<p>Then we tried to compile everything using <em>ts-loader</em> and then recompile it again using <em>babel</em> to ensure (as we initially thought would be wise) backwards compatibility. We also couldn&#8217;t make it working.</p>



<p><strong>Finally, we decided to compile everything &#8211; both JavaScript and TypeScript files &#8211; using <em>ts-loader</em></strong> (including React files). It worked, except source code maps. When we tried to debug in Chrome console it seemed the source code is not refreshing properly after rebuilding. Breakpoints were often not hit and the debugging didn&#8217;t seem right. </p>



<p>After a bit of struggling we found a solution. We set <a href="https://webpack.js.org/configuration/devtool/" target="_blank" rel="noreferrer noopener">devtool</a> webpack option to <em>eval-source-map</em> and configured <em><a href="https://www.npmjs.com/package/source-map-loader" target="_blank" rel="noreferrer noopener">source-map-loader</a></em> for <em>.js</em> files. Finally, the proper part of webpack config looks as follows:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist105110022" 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-webpack_partial-config-js" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="webpack_partial.config.js content, created by dsibinski on 09:40AM on August 29, 2020."
    >

        
<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="webpack_partial.config.js">
        <tr>
          <td id="file-webpack_partial-config-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-webpack_partial-config-js-LC1" class="blob-code blob-code-inner js-file-line">devtool: &quot;eval-source-map&quot;,</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-webpack_partial-config-js-LC2" class="blob-code blob-code-inner js-file-line">module: {</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-webpack_partial-config-js-LC3" class="blob-code blob-code-inner js-file-line">    rules: [</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-webpack_partial-config-js-LC4" class="blob-code blob-code-inner js-file-line">        { </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-webpack_partial-config-js-LC5" class="blob-code blob-code-inner js-file-line">            enforce: &quot;pre&quot;, </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-webpack_partial-config-js-LC6" class="blob-code blob-code-inner js-file-line">            test: /\.js$/, </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-webpack_partial-config-js-LC7" class="blob-code blob-code-inner js-file-line">            exclude: /node_modules/, </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-webpack_partial-config-js-LC8" class="blob-code blob-code-inner js-file-line">            loader: &quot;source-map-loader&quot; </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-webpack_partial-config-js-LC9" class="blob-code blob-code-inner js-file-line">        },</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-webpack_partial-config-js-LC10" class="blob-code blob-code-inner js-file-line">        {</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-webpack_partial-config-js-LC11" class="blob-code blob-code-inner js-file-line">            test: /\.(t|j)sx?$/,</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-webpack_partial-config-js-LC12" class="blob-code blob-code-inner js-file-line">            exclude: /node_modules/,</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-webpack_partial-config-js-LC13" class="blob-code blob-code-inner js-file-line">            use: { </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-webpack_partial-config-js-LC14" class="blob-code blob-code-inner js-file-line">                loader: &#39;ts-loader&#39;</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-webpack_partial-config-js-LC15" class="blob-code blob-code-inner js-file-line">            }</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-webpack_partial-config-js-LC16" class="blob-code blob-code-inner js-file-line">        },  </td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-webpack_partial-config-js-LC17" class="blob-code blob-code-inner js-file-line">    ],</td>
        </tr>
        <tr>
          <td id="file-webpack_partial-config-js-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-webpack_partial-config-js-LC18" 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/2cb3c4c10fe63a9020508c20fa31eef3/raw/6e5f9baf9bf87fec5c43cccf25e5610607c36fa6/webpack_partial.config.js" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/2cb3c4c10fe63a9020508c20fa31eef3#file-webpack_partial-config-js" class="Link--inTextBlock">
          webpack_partial.config.js
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>So far we also haven&#8217;t noticed any issues related to backwards compatibility that were theoretically solved by <em>babel</em>. TypeScript compiler does its job very well.</p>



<h3 class="wp-block-heading">Complicated JS -&gt; TS refactoring</h3>



<p>I found out that JS to TS refactoring is not always an easy task. <strong>Some things that are allowed by JavaScript are not valid in TypeScript</strong>. In most cases it means that something was wrong with your JavaScript code, but we all know how it is with legacy code refactoring <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 class="has-dark-gray-color has-text-color">As an example, we had several functions that we added to a <span style="color:#ef7604" class="tadv-color">String</span> prototype in JavaScript:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist105110060" 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_prototype_helpers-js" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="string_prototype_helpers.js content, created by dsibinski on 09:47AM on August 29, 2020."
    >

        
<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="string_prototype_helpers.js">
        <tr>
          <td id="file-string_prototype_helpers-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-string_prototype_helpers-js-LC1" class="blob-code blob-code-inner js-file-line">String.prototype.contains = function (it) {</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-string_prototype_helpers-js-LC2" class="blob-code blob-code-inner js-file-line">        return this.indexOf(it) != -1;</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-string_prototype_helpers-js-LC3" 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/5e9553424d7441fddefee5f2519ad6dc/raw/d67095fec29dee3eda04be5994faa58f7f94cee7/string_prototype_helpers.js" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/5e9553424d7441fddefee5f2519ad6dc#file-string_prototype_helpers-js" class="Link--inTextBlock">
          string_prototype_helpers.js
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Such code becomes invalid in TypeScript:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="782" height="174" data-attachment-id="3862" data-permalink="https://www.codejourney.net/is-it-worth-migrating-to-typescript/typescript_prototype_functions_error/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?fit=782%2C174&amp;ssl=1" data-orig-size="782,174" 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="TypeScript_prototype_functions_error" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?fit=782%2C174&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?resize=782%2C174&#038;ssl=1" alt="Migrating to TypeScript: TS error about non-existing function on String prototype in VS Code" class="wp-image-3862" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?w=782&amp;ssl=1 782w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?resize=300%2C67&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?resize=768%2C171&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?resize=676%2C150&amp;ssl=1 676w" sizes="auto, (max-width: 782px) 100vw, 782px" /><figcaption>TypeScript complaining about non-existing function</figcaption></figure>



<p>A non-obvious solution to that issue is to extend <span style="color:#ef7604" class="tadv-color">String</span> interface by declaring typed functions you want to add:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist105110103" 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_prototype_helpers-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="string_prototype_helpers.ts content, created by dsibinski on 09:53AM on August 29, 2020."
    >

        
<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="string_prototype_helpers.ts">
        <tr>
          <td id="file-string_prototype_helpers-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-string_prototype_helpers-ts-LC1" class="blob-code blob-code-inner js-file-line">interface String {</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-string_prototype_helpers-ts-LC2" class="blob-code blob-code-inner js-file-line">    contains(this : string, it : any): boolean;</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-string_prototype_helpers-ts-LC3" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-string_prototype_helpers-ts-LC4" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-string_prototype_helpers-ts-LC5" class="blob-code blob-code-inner js-file-line">String.prototype.contains = function (it) {</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-string_prototype_helpers-ts-LC6" class="blob-code blob-code-inner js-file-line">    return this.indexOf(it) != -1;</td>
        </tr>
        <tr>
          <td id="file-string_prototype_helpers-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-string_prototype_helpers-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/f0cd64ae8967aee9a0cfc13409259e1f/raw/92dd7b6a53393c445096b7b63ba08149acf256c5/string_prototype_helpers.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/f0cd64ae8967aee9a0cfc13409259e1f#file-string_prototype_helpers-ts" class="Link--inTextBlock">
          string_prototype_helpers.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>There are more subtle difficulties like that you can meet while migrating JS code to TypeScript. However, in the end it gives you a possibility to make your codebase better.</p>



<h3 class="wp-block-heading">Keeping view models in sync</h3>



<p>An issue I didn&#8217;t think about before migrating to TypeScript was a need to keep frontend and backend view models in sync.</p>



<p>One of the first things you&#8217;d like to have in your TypeScript codebase is to have as much typed data as possible. We use .NET and C# as the backend of our application. ASP.NET MVC controllers returned the strongly-typed objects into the previously chaotic and untyped JS world. Now we are strongly-typed with TypeScript, so we&#8217;d like all this data typed as well <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>Here comes the problem. First of all <strong>our C# data models which we returned from the controllers were not the best</strong>. In most cases we returned a DTO object which contained many properties from which only few were used by JavaScript code. We never saw this problem, because in JS we just dynamically typed properties names we wanted to use. We didn&#8217;t see how much of not needed data is sent from ASP controllers to the web browser.</p>



<p>Now <strong>with TypeScript we needed to create these objects definitions also in TypeScript</strong>. Having a huge DTO object returned from the controller, with another X objects on which this DTO depends, it was a nightmare. <strong>It turned out that for a single DTO I had to create 10-15 TypeScript objects just to use 5-10 properties in the frontend code!</strong></p>



<p>That&#8217;s the moment when we came to the necessity of <strong>creating web view models</strong>. The idea is to <strong>return a view model from a controller, not the whole DTO object. This view model contains only the data which is needed by TypeScript (frontend)</strong>.</p>



<p>I think this is nothing new for experienced web developers. However, now comes the question: <strong>how do we keep backend (C#) view models in sync with frontend (TypeScript) ones?</strong></p>



<p>Unfortunately, I haven&#8217;t found a perfect solution for that. The best method I came up with is&#8230; <strong>manually keeping these view models in sync</strong>. </p>



<p>There&#8217;s a <a href="https://marketplace.visualstudio.com/items?itemName=adrianwilczynski.csharp-to-typescript" target="_blank" rel="noreferrer noopener">C# to TypeScript</a> VS Code extension which allows to paste the copied C# code as its TypeScript equivalent. It makes the job a bit easier. It even has a <a href="https://www.nuget.org/packages/CSharpToTypeScript.CLITool/" target="_blank" rel="noreferrer noopener">CLI tool</a>, but it produces a single <em>.ts</em> file from a single <em>.cs</em> file. If you have multiple objects in a single C# file it will produce a single TypeScript file with all these objects. If any of those objects is used in other files (unfortunately we have many of such cases), these dependencies will not be automatically added as imports in the auto-generated <em>.ts</em> files.</p>



<p>However, I don&#8217;t find it very problematic for now. As soon as the TS view models are created, we just need to update them as often as we update C# view models. I think this is a very common issue so if you know any better solution here &#8211; please share 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>



<h2 class="wp-block-heading">Migrating to TypeScript &#8211; summary</h2>



<p>Migrating to TypeScript has been a very interesting and rewarding process. Compared to vanilla JavaScript, TypeScript lets programmers see many problems. This allows to see how bad our codebase was. We even realized that our server-side C# code was not the best (see the section about view models above). Thanks to introducing TypeScript we improved a lot of our JavaScript and C# code, including its architecture.</p>



<p>I think that TypeScript uses many simple concepts under the hood and it makes a lot of things possible (see <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types" target="_blank" rel="noreferrer noopener">keyof</a> or <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types" target="_blank" rel="noreferrer noopener">unknown</a>). In many cases TypeScript <em>lets</em> you do something, but <em>doesn&#8217;t force</em> you to do it. That&#8217;s the beauty of this typed JavaScript world <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/is-it-worth-migrating-to-typescript/">Is It Worth Migrating to TypeScript?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/is-it-worth-migrating-to-typescript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3840</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">  <span class=pl-k>var</span> <span class=pl-s1>array</span> <span class=pl-c1>=</span> <span class=pl-k>new</span><span class=pl-kos>[</span><span class=pl-kos>]</span> <span class=pl-kos>{</span> <span class=pl-s>&#39;A&#39;</span><span class=pl-kos>,</span> <span class=pl-s>&#39;B&#39;</span><span class=pl-kos>,</span> <span class=pl-s>&#39;C&#39;</span><span class=pl-kos>,</span> <span class=pl-s>&#39;D&#39;</span><span class=pl-kos>,</span> <span class=pl-s>&#39;E&#39;</span><span class=pl-kos>,</span> <span class=pl-s>&#39;F&#39;</span><span class=pl-kos>,</span> <span class=pl-s>&#39;G&#39;</span> <span class=pl-kos>,</span> <span class=pl-s>&#39;H&#39;</span><span class=pl-kos>}</span><span class=pl-kos>;</span></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">  <span class=pl-k>var</span> <span class=pl-s1>arraySlice</span> <span class=pl-c1>=</span> <span class=pl-s1>array</span><span class=pl-kos>.</span><span class=pl-en>Skip</span><span class=pl-kos>(</span><span class=pl-c1>1</span><span class=pl-kos>)</span><span class=pl-kos>.</span><span class=pl-en>Take</span><span class=pl-kos>(</span><span class=pl-c1>3</span><span class=pl-kos>)</span><span class=pl-kos>.</span><span class=pl-en>ToArray</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// contains &#39;B&#39;, &#39;C&#39; and &#39;D&#39;</span></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">  <span class=pl-k>var</span> <span class=pl-s1>story</span> <span class=pl-c1>=</span> <span class=pl-s>&quot;C# 8 is going to be great!&quot;</span><span class=pl-kos>;</span></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">  <span class=pl-s1>Console</span><span class=pl-kos>.</span><span class=pl-en>WriteLine</span><span class=pl-kos>(</span><span class=pl-s1>story</span><span class=pl-kos>[</span><span class=pl-c1>^</span><span class=pl-c1>6</span>..<span class=pl-c1>^</span><span class=pl-c1>0</span><span class=pl-kos>]</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// prints &quot;great!&quot; (last 6 chars)</span></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>10 Most Shocking JavaScript Features for C# Developers</title>
		<link>https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/</link>
					<comments>https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 07 Nov 2018 14:00:43 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=2999</guid>

					<description><![CDATA[<p>Whether you&#8217;re a C# (or similar language like Java) developer eager to learn JavaScript or you&#8217;ve already been working with JS for some time, I hope you find this article interesting. I collected for you 10 JavaScript features which are/were the most shocking for C# developers who learnt JavaScript. These features of JavaScript language are the&#8230;</p>
<p>The post <a href="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/">10 Most Shocking JavaScript Features for C# Developers</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Whether you&#8217;re a C# (or similar language like Java) developer eager to learn JavaScript or you&#8217;ve already been working with JS for some time, I hope you find this article interesting. I collected for you <strong>10 JavaScript features which are/were the most shocking for C# developers</strong> who learnt JavaScript.</p>
<p><span id="more-2999"></span></p>
<p>These features of JavaScript language are the most striking differences compared to C# ecosystem. If you&#8217;re about to learn JavaScript, sooner or later you&#8217;ll also have to deal with them.</p>
<p><span style="font-size: 10pt;"><em>Before we begin, one disclaimer: the goal of this post isn&#8217;t stating which language is better or worse. JavaScript and C# are different programming languages and their use cases are also completely different. One is better for some usages, while the other is better for others. The list is <a href="https://twitter.com/DawidSibinski/status/1056998751234113536" target="_blank" rel="noopener">my and other readers&#8217;</a> subjective one and you don&#8217;t need to agree with all points. I&#8217;m myself a C# developer on my JavaScript learning journey, so I&#8217;d like to help you grasping these confusing concepts <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;" /></em></span></p>
<h1>1. Dynamic Typing</h1>
<p>Obviously, the first difference JavaScript newbie notices is that the language is <strong>dynamically-typed</strong>. It means that the <strong>types</strong> (of variables, functions, actually of almost everything) <strong>are checked at runtime</strong>, <strong>not at compile time</strong> like in C# or Java.</p>
<p>Because of that, there&#8217;s not much difference in defining variables and assigning them data of various <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" target="_blank" rel="noopener">data types</a>:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874493" 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-ja-variablestypes-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JA-variablesTypes.js content, created by dsibinski on 05:47PM on November 06, 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="JA-variablesTypes.js">
<tr>
<td id="file-ja-variablestypes-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-ja-variablestypes-js-LC1" class="blob-code blob-code-inner js-file-line">  var someNumber = 1;</td>
</tr>
<tr>
<td id="file-ja-variablestypes-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-ja-variablestypes-js-LC2" class="blob-code blob-code-inner js-file-line">  var someBoolean = true;</td>
</tr>
<tr>
<td id="file-ja-variablestypes-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-ja-variablestypes-js-LC3" class="blob-code blob-code-inner js-file-line">  var someString = &#39;Hello JS!&#39;;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/d2b8e6303e99cf7fe98280eed7d31f82/raw/8c1465a21bee34cd735a3a9b9481bd6eae602f38/JA-variablesTypes.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/d2b8e6303e99cf7fe98280eed7d31f82#file-ja-variablestypes-js" class="Link--inTextBlock"><br />
          JA-variablesTypes.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>JavaScript&#8217;s variables are not associated with any particular data type. That&#8217;s why it&#8217;s completely legit to write something like that:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874504" 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-js_dynamic-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_dynamic.js content, created by dsibinski on 05:48PM on November 06, 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="JS_dynamic.js">
<tr>
<td id="file-js_dynamic-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_dynamic-js-LC1" class="blob-code blob-code-inner js-file-line">  var a = 1;         // typeof a =&gt; number</td>
</tr>
<tr>
<td id="file-js_dynamic-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_dynamic-js-LC2" class="blob-code blob-code-inner js-file-line">  a = true;          // typeof a =&gt; boolean</td>
</tr>
<tr>
<td id="file-js_dynamic-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_dynamic-js-LC3" class="blob-code blob-code-inner js-file-line">  a = &#39;Hello JS!&#39;;   // typeof a =&gt; string</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/a0261ec670ae6d49f344956b825c9627/raw/3d80658605472ec71a8ebaee4c1fd59b87281834/JS_dynamic.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/a0261ec670ae6d49f344956b825c9627#file-js_dynamic-js" class="Link--inTextBlock"><br />
          JS_dynamic.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Because JavaScript is dynamically-typed, issues with types are detected at runtime (e.g. error is thrown as soon as you try to use a variable in a context which expects another data type), not during compilation time as it would be in C# or Java.</p>
<p>If you have some experience with statically-typed languages, you may now feel how much confusion and troubles dynamic typing can bring. At least at the beginning.</p>
<h1>2. Implicit types coercion</h1>
<div>JavaScript has one more interesting feature &#8211; <strong>types coercion</strong>. Even though this term&#8217;s name sounds a bit weird <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&#8217;s quite simple: types coercion happens when a <strong>value of one type is converted to another one</strong>.</div>
<div> </div>
<div>It may be explicit, but harder to grasp is the <strong>implicit types coercion</strong>. It means that developer doesn&#8217;t necessarily ask for converting value of some type to another, but it still happens &#8220;silently&#8221;. To visualize it, consider the following code:</div>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874409" 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-js_typescoercion-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_typesCoercion.js content, created by dsibinski on 05:42PM on November 06, 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="JS_typesCoercion.js">
<tr>
<td id="file-js_typescoercion-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_typescoercion-js-LC1" class="blob-code blob-code-inner js-file-line">  var name, isGreatDeveloper;</td>
</tr>
<tr>
<td id="file-js_typescoercion-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_typescoercion-js-LC2" class="blob-code blob-code-inner js-file-line">  name = &#39;Dawid&#39;;</td>
</tr>
<tr>
<td id="file-js_typescoercion-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_typescoercion-js-LC3" class="blob-code blob-code-inner js-file-line">  isGreatDeveloper = true;</td>
</tr>
<tr>
<td id="file-js_typescoercion-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-js_typescoercion-js-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_typescoercion-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-js_typescoercion-js-LC5" class="blob-code blob-code-inner js-file-line">  console.log(&#39;Is &#39; + name + &#39; a great dev?: &#39; + isGreatDeveloper); </td>
</tr>
<tr>
<td id="file-js_typescoercion-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-js_typescoercion-js-LC6" class="blob-code blob-code-inner js-file-line">  // displays &#39;Is Dawid a great dev?: true&#39;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/ad25af60a0cfee06066f72cd7ccbc5ab/raw/136633dc5779e33da22d14658ef3daab76610df0/JS_typesCoercion.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/ad25af60a0cfee06066f72cd7ccbc5ab#file-js_typescoercion-js" class="Link--inTextBlock"><br />
          JS_typesCoercion.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<div>Even though <span style="color: #ff6600;">console.log()</span> expects data of text type, <span style="color: #ff6600;">isGreatDeveloper</span> which holds a <em>boolean</em> value at the moment is implicitly converted to text.</p>
</div>
<div>The above example was just to show you what types coercion is all about, but it gets more confusing in reality. First misleading concept is that JS has actually two equality operators: <span style="color: #ff6600;">==</span> and <span style="color: #ff6600;">===</span>.</p>
</div>
<div>Let&#8217;s see some code example to know the difference between them:</div>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874715" 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-js_equalityoperators-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_equalityOperators.js content, created by dsibinski on 06:01PM on November 06, 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="JS_equalityOperators.js">
<tr>
<td id="file-js_equalityoperators-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_equalityoperators-js-LC1" class="blob-code blob-code-inner js-file-line">  var age = 26;</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_equalityoperators-js-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_equalityoperators-js-LC3" class="blob-code blob-code-inner js-file-line">  if(age == &#39;26&#39;){</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-js_equalityoperators-js-LC4" class="blob-code blob-code-inner js-file-line">      // this is executed</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-js_equalityoperators-js-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-js_equalityoperators-js-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-js_equalityoperators-js-LC7" class="blob-code blob-code-inner js-file-line">  if(age === &#39;26&#39;){</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-js_equalityoperators-js-LC8" class="blob-code blob-code-inner js-file-line">      // this is NOT executed</td>
</tr>
<tr>
<td id="file-js_equalityoperators-js-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-js_equalityoperators-js-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/c509a2162e81f44e34d2995f2a8e08bd/raw/08ca99ee63291d8b599282c3489a0d383d5a8a8c/JS_equalityOperators.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c509a2162e81f44e34d2995f2a8e08bd#file-js_equalityoperators-js" class="Link--inTextBlock"><br />
          JS_equalityOperators.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<div>The first <strong><span style="color: #ff6600;">==</span> operator performs an implicit types coercion before performing the actual comparison</strong>. That&#8217;s why the text &#8217;26&#8217; is &#8220;silently&#8221; converted to a number 26 and the <em>if</em> statement is <em>true</em> at this point.</p>
</div>
<div>Because of that, we should normally always use <span style="color: #ff6600;">===</span> operator to avoid such unclear situations.</p>
</div>
<div>Existence of such (and many more) nice concepts of JavaScript leads to finding such interesting Tweets:</div>
<div align="center">
<blockquote class="twitter-tweet" data-lang="en">
<p dir="ltr" lang="en">*shuts laptop forever* <a href="https://t.co/3GS1JfNDSP">pic.twitter.com/3GS1JfNDSP</a></p>
<p>— Shayna Gentiluomo (@kd2luw) <a href="https://twitter.com/kd2luw/status/992096570802765824?ref_src=twsrc%5Etfw">May 3, 2018</a></p>
</blockquote>
<p><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p>
</div>
<div>If you want to dig into types coercion, you can read <a href="https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839" target="_blank" rel="noopener">this article</a>.</div>
<h1>3. <em>null</em> and <em>undefined</em></h1>
<p>In JavaScript there are two values which represent kind of unassigned variables: <em>undefined</em> and <em>null</em>. What&#8217;s the difference between them? The snippet below clarifies:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874833" 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-js_null_undefined-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_null_undefined.js content, created by dsibinski on 06:10PM on November 06, 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="JS_null_undefined.js">
<tr>
<td id="file-js_null_undefined-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_null_undefined-js-LC1" class="blob-code blob-code-inner js-file-line">  var x;</td>
</tr>
<tr>
<td id="file-js_null_undefined-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_null_undefined-js-LC2" class="blob-code blob-code-inner js-file-line">  console.log(x); // prints &#39;undefined&#39;</td>
</tr>
<tr>
<td id="file-js_null_undefined-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_null_undefined-js-LC3" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_null_undefined-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-js_null_undefined-js-LC4" class="blob-code blob-code-inner js-file-line">  x = null;</td>
</tr>
<tr>
<td id="file-js_null_undefined-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-js_null_undefined-js-LC5" class="blob-code blob-code-inner js-file-line">  console.log(x); // prints &#39;null&#39;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/be2f7e534a64b397cf351fc9e02517f3/raw/8ae993119a9b05faa44c09edd390eabe04166381/JS_null_undefined.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/be2f7e534a64b397cf351fc9e02517f3#file-js_null_undefined-js" class="Link--inTextBlock"><br />
          JS_null_undefined.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<div>As soon as you declare a variable, but don&#8217;t assign any value to it, it contains <em>undefined</em>. It may contain <em>null</em> if it was assigned to it, either explicitly as in the example or as a result of some operation.</p>
</div>
<div>I see it as the names suggest: <strong><em>undefined</em></strong> is something that <strong>has really not been defined</strong> (assigned) yet, while <strong><em>null</em> </strong>is more like a special <strong>kind of value which has some useful meaning</strong>.</div>
<div>
<h1>4. Truly and Falsy values</h1>
<div>As we already know <em>null</em> and <em>undefined</em>,  it&#8217;s important to note that there are some &#8220;falsy&#8221; and &#8220;truly&#8221; values in JavaScript:</div>
<ul>
<li>&#8220;falsy&#8221; values: <em>undefined</em>, <em>null</em>, <em>0,</em> <em>&#8221;</em>, <em>NaN</em></li>
<li>&#8220;truly&#8221; values: all NOT falsy values</li>
</ul>
<div>It means that &#8220;falsy&#8221; values are implicitly converted to <em>false</em> <em>boolean</em> value e.g. in comparison context:</div>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874876" 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-js_falsy-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_falsy.js content, created by dsibinski on 06:12PM on November 06, 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="JS_falsy.js">
<tr>
<td id="file-js_falsy-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_falsy-js-LC1" class="blob-code blob-code-inner js-file-line">  var x; // x is &#39;undefined&#39;</td>
</tr>
<tr>
<td id="file-js_falsy-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_falsy-js-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_falsy-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_falsy-js-LC3" class="blob-code blob-code-inner js-file-line">  if(x){</td>
</tr>
<tr>
<td id="file-js_falsy-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-js_falsy-js-LC4" class="blob-code blob-code-inner js-file-line">      // this is NOT executed</td>
</tr>
<tr>
<td id="file-js_falsy-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-js_falsy-js-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/78f259ce6528f4bcbe4574f12ac6417b/raw/b10f88989d1f4a0f6316d9b9a179c1c2a82a3c77/JS_falsy.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/78f259ce6528f4bcbe4574f12ac6417b#file-js_falsy-js" class="Link--inTextBlock"><br />
          JS_falsy.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Knowing that you might want to check if the value has been defined in the following way:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874887" 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-js_definedcheckwrong-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_definedCheckWrong.js content, created by dsibinski on 06:13PM on November 06, 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="JS_definedCheckWrong.js">
<tr>
<td id="file-js_definedcheckwrong-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_definedcheckwrong-js-LC1" class="blob-code blob-code-inner js-file-line">  if(x){</td>
</tr>
<tr>
<td id="file-js_definedcheckwrong-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_definedcheckwrong-js-LC2" class="blob-code blob-code-inner js-file-line">      console.log(&#39;x is defined!&#39;);</td>
</tr>
<tr>
<td id="file-js_definedcheckwrong-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_definedcheckwrong-js-LC3" 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/d6b3fcdc60f8df404aaa0a2d96e8c57e/raw/39700b4b317fd7ac3896d486bf23fb5d8a7f0a29/JS_definedCheckWrong.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/d6b3fcdc60f8df404aaa0a2d96e8c57e#file-js_definedcheckwrong-js" class="Link--inTextBlock"><br />
          JS_definedCheckWrong.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<div>However, assuming <span style="color: #ff6600;">x</span> is a number, this will not work if <span style="color: #ff6600;">x</span> has a value of <em>0</em>, which is also one of the &#8220;falsy&#8221; values.<br />
So the proper way of checking whether the number has been defined is as follows:</div>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92875102" 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-js_definedcheckcorrect-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_definedCheckCorrect.js content, created by dsibinski on 06:29PM on November 06, 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="JS_definedCheckCorrect.js">
<tr>
<td id="file-js_definedcheckcorrect-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_definedcheckcorrect-js-LC1" class="blob-code blob-code-inner js-file-line">  if(x || x === 0){</td>
</tr>
<tr>
<td id="file-js_definedcheckcorrect-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_definedcheckcorrect-js-LC2" class="blob-code blob-code-inner js-file-line">      console.log(&#39;x is defined!&#39;);</td>
</tr>
<tr>
<td id="file-js_definedcheckcorrect-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_definedcheckcorrect-js-LC3" 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/35a7702884c752f5de1f4dbb4d8ff1d7/raw/a5d0c3d2d6198603ad8ab570b5345a0f2745ea7d/JS_definedCheckCorrect.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/35a7702884c752f5de1f4dbb4d8ff1d7#file-js_definedcheckcorrect-js" class="Link--inTextBlock"><br />
          JS_definedCheckCorrect.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Of course, for another data types (like text) you need to handle other &#8220;falsy&#8221; values as well. It depends what you consider a meaningful value.</p>
</div>
<h1>5. Hoisting</h1>
<p>In JavaScript you can legally write such a code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874773" 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-js_hoisting-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_hoisting.js content, created by dsibinski on 06:06PM on November 06, 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="JS_hoisting.js">
<tr>
<td id="file-js_hoisting-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_hoisting-js-LC1" class="blob-code blob-code-inner js-file-line">  name = &#39;Dawid&#39;;</td>
</tr>
<tr>
<td id="file-js_hoisting-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_hoisting-js-LC2" class="blob-code blob-code-inner js-file-line">  console.log(name);</td>
</tr>
<tr>
<td id="file-js_hoisting-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_hoisting-js-LC3" class="blob-code blob-code-inner js-file-line">  var name;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/6624f7742d1f05cfad7ea30a023a71e3/raw/42d05b4060261630986efe9b275946d50bba8032/JS_hoisting.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/6624f7742d1f05cfad7ea30a023a71e3#file-js_hoisting-js" class="Link--inTextBlock"><br />
          JS_hoisting.js<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 notice, <span style="color: #ff6600;">name</span> <strong>variable is used before it&#8217;s declared</strong> 2 lines below. This is maybe not that weird, as in JS we can even declare variables without the <span style="color: #ff6600;">var</span> keyword, but we can do the same with functions:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874785" 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-js_hoisting_functions-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_hoisting_functions.js content, created by dsibinski on 06:07PM on November 06, 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="JS_hoisting_functions.js">
<tr>
<td id="file-js_hoisting_functions-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_hoisting_functions-js-LC1" class="blob-code blob-code-inner js-file-line">  printHello(); // prints &#39;Hello!&#39;</td>
</tr>
<tr>
<td id="file-js_hoisting_functions-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_hoisting_functions-js-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_hoisting_functions-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_hoisting_functions-js-LC3" class="blob-code blob-code-inner js-file-line">  function printHello(){</td>
</tr>
<tr>
<td id="file-js_hoisting_functions-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-js_hoisting_functions-js-LC4" class="blob-code blob-code-inner js-file-line">      console.log(&#39;Hello!&#39;);</td>
</tr>
<tr>
<td id="file-js_hoisting_functions-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-js_hoisting_functions-js-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/045d0c12cb31565baad369a3f6e1f373/raw/12a8f254043f6b23608d075c59212729f2743270/JS_hoisting_functions.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/045d0c12cb31565baad369a3f6e1f373#file-js_hoisting_functions-js" class="Link--inTextBlock"><br />
          JS_hoisting_functions.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>So here we call the function before declaring it. Why does this work?</p>
<p>This works thanks to <strong>hoisting</strong>. It&#8217;s a compile-time mechanism which <strong>&#8220;moves&#8221; all variables and functions declarations to the top of our JavaScript code</strong>. In fact, during the execution of above-listed code, JavaScript engine processes variables and functions declarations before executing any other code.</p>
<p>It however applies only to declarations, not to assignments:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92874805" 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-js_hoisting_declarations-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="JS_hoisting_declarations.js content, created by dsibinski on 06:08PM on November 06, 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="JS_hoisting_declarations.js">
<tr>
<td id="file-js_hoisting_declarations-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-js_hoisting_declarations-js-LC1" class="blob-code blob-code-inner js-file-line">  console.log(name); // prints &#39;undefined&#39;</td>
</tr>
<tr>
<td id="file-js_hoisting_declarations-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-js_hoisting_declarations-js-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-js_hoisting_declarations-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-js_hoisting_declarations-js-LC3" class="blob-code blob-code-inner js-file-line">  var name = 5;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/43f61dbfadb5a1d017039024b2b23f16/raw/17efcaca3652487875c5de628cd7e12375415e72/JS_hoisting_declarations.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/43f61dbfadb5a1d017039024b2b23f16#file-js_hoisting_declarations-js" class="Link--inTextBlock"><br />
          JS_hoisting_declarations.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<div>In this case, only <span style="color: #ff6600;">var name</span> part of the declaration and assignment is &#8220;moved to the top&#8221; and executed first. The assignment part (<span style="color: #ff6600;">=5</span>) is not. That&#8217;s why when calling <span style="color: #ff6600;">console.log(name)</span> the <span style="color: #ff6600;">name</span> variable is <em>undefined</em>.</p>
</div>
<div>Because of hoisting, we should declare and preferably assign all variables used in the given scope at the top of it.</div>
<h1>6. Lexical scoping and <em>this</em> keyword</h1>
<p>To create a scope (space in which the variables defined in it are accessible) in JS, we need to create a new function. Variable defined in a function is not accessible outside this function:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92876193" 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-functionscope-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="FunctionScope.js content, created by dsibinski on 07:31PM on November 06, 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="FunctionScope.js">
<tr>
<td id="file-functionscope-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-functionscope-js-LC1" class="blob-code blob-code-inner js-file-line">  function a() {</td>
</tr>
<tr>
<td id="file-functionscope-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-functionscope-js-LC2" class="blob-code blob-code-inner js-file-line">      var x = 5;</td>
</tr>
<tr>
<td id="file-functionscope-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-functionscope-js-LC3" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-functionscope-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-functionscope-js-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-functionscope-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-functionscope-js-LC5" class="blob-code blob-code-inner js-file-line">  console.log(x); // Uncaught ReferenceError: </td>
</tr>
<tr>
<td id="file-functionscope-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-functionscope-js-LC6" class="blob-code blob-code-inner js-file-line">                  // x is not defined</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/73fa86f7173ec8a2523f0256fb24bab9/raw/a877636b5fa397cb9695972bf5cc2b8b60ea2046/FunctionScope.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/73fa86f7173ec8a2523f0256fb24bab9#file-functionscope-js" class="Link--inTextBlock"><br />
          FunctionScope.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>It means that other blocks like the ones associated with <em>if</em> statement don&#8217;t introduce a new scope:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92876215" 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-ifblock-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="IfBlock.cs content, created by dsibinski on 07:32PM on November 06, 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="IfBlock.cs">
<tr>
<td id="file-ifblock-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-ifblock-cs-LC1" class="blob-code blob-code-inner js-file-line">  if(true) {</td>
</tr>
<tr>
<td id="file-ifblock-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-ifblock-cs-LC2" class="blob-code blob-code-inner js-file-line">      var x = 5;</td>
</tr>
<tr>
<td id="file-ifblock-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-ifblock-cs-LC3" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-ifblock-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-ifblock-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-ifblock-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-ifblock-cs-LC5" class="blob-code blob-code-inner js-file-line">  console.log(x); // prints &#39;5&#39;</td>
</tr>
<tr>
<td id="file-ifblock-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-ifblock-cs-LC6" class="blob-code blob-code-inner js-file-line">                  // x is a global scope variable</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/096fc8e846dcea4b8e0eef6bd5783969/raw/4ce0e4dc8d8c0a297b26e0b2b7be42a2b7c7b206/IfBlock.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/096fc8e846dcea4b8e0eef6bd5783969#file-ifblock-cs" class="Link--inTextBlock"><br />
          IfBlock.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>If a variable is defined outside of any function, it&#8217;s assigned to a <strong>global scope</strong>.</p>
<p>However, in JavaScript we also have something called <strong>lexical scoping</strong>. It basically <strong>makes functions declared within another functions having access to the parent function&#8217;s scope</strong>, as the following example presents<strong>:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92877551" 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-lexicalscoping-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="LexicalScoping.js content, created by dsibinski on 09:06PM on November 06, 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="LexicalScoping.js">
<tr>
<td id="file-lexicalscoping-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-lexicalscoping-js-LC1" class="blob-code blob-code-inner js-file-line">  function a() {</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-lexicalscoping-js-LC2" class="blob-code blob-code-inner js-file-line">      var x = &#39;Hello&#39;;</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-lexicalscoping-js-LC3" class="blob-code blob-code-inner js-file-line">      b();</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-lexicalscoping-js-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-lexicalscoping-js-LC5" class="blob-code blob-code-inner js-file-line">      function b() {</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-lexicalscoping-js-LC6" class="blob-code blob-code-inner js-file-line">          var y = &#39; world!&#39;;</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-lexicalscoping-js-LC7" class="blob-code blob-code-inner js-file-line">          console.log(x + y); </td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-lexicalscoping-js-LC8" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-lexicalscoping-js-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-lexicalscoping-js-LC10" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-lexicalscoping-js-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping-js-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-lexicalscoping-js-LC12" class="blob-code blob-code-inner js-file-line">  a(); // prints &#39;Hello world!&#39;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/cae61de9d60e5d23d4db60deb2f0afa7/raw/a242daae4fc84440ffbc6cdeecf048bb1c4207a1/LexicalScoping.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/cae61de9d60e5d23d4db60deb2f0afa7#file-lexicalscoping-js" class="Link--inTextBlock"><br />
          LexicalScoping.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Forming such &#8220;hierarchy&#8221; of functions is also referred to as <strong>scope chain</strong>. You should remember that it refers to the <strong>order in which functions are lexically written, not in which they are called:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92877739" 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-lexicalscoping_wrong-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="LexicalScoping_wrong.js content, created by dsibinski on 09:17PM on November 06, 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="LexicalScoping_wrong.js">
<tr>
<td id="file-lexicalscoping_wrong-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-lexicalscoping_wrong-js-LC1" class="blob-code blob-code-inner js-file-line">  function a() {</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-lexicalscoping_wrong-js-LC2" class="blob-code blob-code-inner js-file-line">      b();</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-lexicalscoping_wrong-js-LC3" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-lexicalscoping_wrong-js-LC4" class="blob-code blob-code-inner js-file-line">      function b() {</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-lexicalscoping_wrong-js-LC5" class="blob-code blob-code-inner js-file-line">          var x = &#39;Hello world!&#39;;</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-lexicalscoping_wrong-js-LC6" class="blob-code blob-code-inner js-file-line">          c();</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-lexicalscoping_wrong-js-LC7" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-lexicalscoping_wrong-js-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-lexicalscoping_wrong-js-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-lexicalscoping_wrong-js-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-lexicalscoping_wrong-js-LC11" class="blob-code blob-code-inner js-file-line">  function c() {</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-lexicalscoping_wrong-js-LC12" class="blob-code blob-code-inner js-file-line">      console.log(x); // Uncaught ReferenceError: </td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-lexicalscoping_wrong-js-LC13" class="blob-code blob-code-inner js-file-line">                      // x is not defined</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-lexicalscoping_wrong-js-LC14" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-lexicalscoping_wrong-js-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-lexicalscoping_wrong-js-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-lexicalscoping_wrong-js-LC16" class="blob-code blob-code-inner js-file-line">  a();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/edf0470e2d6e832298738d41937bbaf7/raw/a93d7b1c2cf952dadd77612c7dc0d22edf8ff499/LexicalScoping_wrong.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/edf0470e2d6e832298738d41937bbaf7#file-lexicalscoping_wrong-js" class="Link--inTextBlock"><br />
          LexicalScoping_wrong.js<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 above, as soon as we call <span style="color: #ff6600;">a()</span>, which then calls <span style="color: #ff6600;">b()</span>, within which we define variable <span style="color: #ff6600;">x</span> and then call function <span style="color: #ff6600;">c()</span>, inside of function <span style="color: #ff6600;">c()</span> we don&#8217;t have access to <span style="color: #ff6600;">x</span> variable (<em>x is not defined</em>). Why does it happen even though function <span style="color: #ff6600;">b()</span> in which <span style="color: #ff6600;">x</span> variable is declared called function <span style="color: #ff6600;">c()</span>? Because <strong>function <span style="color: #ff6600;">c()</span> is not lexically written as the child function of <span style="color: #ff6600;">b()</span></strong>. Parent scope for function <span style="color: #ff6600;">c()</span> is always the global scope.</p>
<h1>7. <em>this</em> keyword</h1>
<p>All these scoping rules examined above somehow lead to another confusing concept with <span style="color: #ff6600;">this</span> keyword. As soon as we define a method on some object and try to print the <span style="color: #ff6600;">this</span> keyword in this object&#8217;s method, the result seems reasonable:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92877952" 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-this_1-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="this_1.js content, created by dsibinski on 09:33PM on November 06, 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="this_1.js">
<tr>
<td id="file-this_1-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-this_1-js-LC1" class="blob-code blob-code-inner js-file-line">  var blogger = {</td>
</tr>
<tr>
<td id="file-this_1-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-this_1-js-LC2" class="blob-code blob-code-inner js-file-line">      name: &#39;Dawid&#39;,</td>
</tr>
<tr>
<td id="file-this_1-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-this_1-js-LC3" class="blob-code blob-code-inner js-file-line">      website: &#39;codejourney.net&#39;,</td>
</tr>
<tr>
<td id="file-this_1-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-this_1-js-LC4" class="blob-code blob-code-inner js-file-line">      aboutMe: function(){</td>
</tr>
<tr>
<td id="file-this_1-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-this_1-js-LC5" class="blob-code blob-code-inner js-file-line">          console.log(this);</td>
</tr>
<tr>
<td id="file-this_1-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-this_1-js-LC6" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-this_1-js-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-this_1-js-LC7" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-this_1-js-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-this_1-js-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-this_1-js-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-this_1-js-LC9" class="blob-code blob-code-inner js-file-line">  blogger.aboutMe(); // prints: {name: &quot;Dawid&quot;, website: &quot;codejourney.net&quot;, aboutMe: ƒ}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/aa92f36cec8f93026b25702bf9798cd7/raw/37b18ae0ceddc5194a838ff7593c071ee29d06f4/this_1.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/aa92f36cec8f93026b25702bf9798cd7#file-this_1-js" class="Link--inTextBlock"><br />
          this_1.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>However, if we just define an inner function in our method and try to print <span style="color: #ff6600;">this</span> keyword inside it, weird stuff happens:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92877991" 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-this_2-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="this_2.js content, created by dsibinski on 09:37PM on November 06, 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="this_2.js">
<tr>
<td id="file-this_2-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-this_2-js-LC1" class="blob-code blob-code-inner js-file-line">  var blogger = {</td>
</tr>
<tr>
<td id="file-this_2-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-this_2-js-LC2" class="blob-code blob-code-inner js-file-line">      name: &#39;Dawid&#39;,</td>
</tr>
<tr>
<td id="file-this_2-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-this_2-js-LC3" class="blob-code blob-code-inner js-file-line">      website: &#39;codejourney.net&#39;,</td>
</tr>
<tr>
<td id="file-this_2-js-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-this_2-js-LC4" class="blob-code blob-code-inner js-file-line">      aboutMe: function(){</td>
</tr>
<tr>
<td id="file-this_2-js-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-this_2-js-LC5" class="blob-code blob-code-inner js-file-line">          function innerFunc(){</td>
</tr>
<tr>
<td id="file-this_2-js-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-this_2-js-LC6" class="blob-code blob-code-inner js-file-line">              console.log(this);</td>
</tr>
<tr>
<td id="file-this_2-js-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-this_2-js-LC7" class="blob-code blob-code-inner js-file-line">          }</td>
</tr>
<tr>
<td id="file-this_2-js-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-this_2-js-LC8" class="blob-code blob-code-inner js-file-line">          innerFunc();   </td>
</tr>
<tr>
<td id="file-this_2-js-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-this_2-js-LC9" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-this_2-js-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-this_2-js-LC10" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-this_2-js-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-this_2-js-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-this_2-js-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-this_2-js-LC12" class="blob-code blob-code-inner js-file-line">  blogger.aboutMe(); // (!!!) prints: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/4219bf76cbdbf55596ac2fb03ab9f49e/raw/c669e8d2d3a687d330ed1377916c5d2954dfe0d7/this_2.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/4219bf76cbdbf55596ac2fb03ab9f49e#file-this_2-js" class="Link--inTextBlock"><br />
          this_2.js<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, the <span style="color: #ff6600;">this</span> keyword in the <span style="color: #ff6600;">innerFunc()</span> function doesn&#8217;t point to the <span style="color: #ff6600;">blogger</span> object anymore. Instead it points to a <span style="color: #ff6600;">Window</span> object, which represents the browser&#8217;s window (<span style="color: #ff6600;">this</span> used in the global scope points to it).</p>
<p>This happens because <strong>in a regular function the <span style="color: #ff6600;">this</span> keyword points to the global object </strong>(<span style="color: #ff6600;">Window</span> object in our case). <span style="color: #ff6600;">innerFunc()</span> is here considered as a regular function, not as an object&#8217;s method. This behavior may be confusing and is often a subject of dispute in JavaScript community.</p>
<h1>8. <em>sort()</em> function</h1>
<p>You&#8217;re a newbie JS developer and you&#8217;d like to sort an array of numbers. You found a <span style="color: #ff6600;">sort()</span> method on the array, so why not to use it? You write such code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92878145" 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-sort_numbers-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="sort_numbers.js content, created by dsibinski on 09:48PM on November 06, 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="sort_numbers.js">
<tr>
<td id="file-sort_numbers-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-sort_numbers-js-LC1" class="blob-code blob-code-inner js-file-line">  var numbers = [40, 20, 15, -5, 7];</td>
</tr>
<tr>
<td id="file-sort_numbers-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-sort_numbers-js-LC2" class="blob-code blob-code-inner js-file-line">  console.log(numbers.sort());</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/5714737927db7c97af0de9a26d994298/raw/60baaa4c93ce3b0cec31593ab4cb9d97934291ae/sort_numbers.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/5714737927db7c97af0de9a26d994298#file-sort_numbers-js" class="Link--inTextBlock"><br />
          sort_numbers.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>What do you expect to be logged in the console? Let&#8217;s see:</p>
<blockquote>
<p>(5) [-5, 15, 20, 40, 7]</p>
</blockquote>
<p>Nice! What happens here? 7 is greater than 40? Well, yes <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 works as expected, because the <span style="color: #ff6600;">sort()</span> function sorts array&#8217;s elements as strings and alphabetically. Therefore, if our array contains numbers, the final order depends on the Unicode representations values of each number.</p>
<p>Fortunately, there are <a href="https://www.w3schools.com/js/js_array_sort.asp" target="_blank" rel="noopener">ways to use <span style="color: #ff6600;">sort()</span> function correctly for numbers</a>, but this functionality is still confusing for new JavaScript developers.</p>
<h1>9. Prototypes</h1>
<p>Every object in JavaScript has a <span style="color: #ff6600;">__proto__</span> property. We can access it directly on our object or by using <span style="color: #ff6600;">Object.getPrototypeOf()</span> method. In both cases, having created an empty object and printing its prototype to the console like that:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92878559" 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-prorotype-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Prorotype.js content, created by dsibinski on 10:17PM on November 06, 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="Prorotype.js">
<tr>
<td id="file-prorotype-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-prorotype-js-LC1" class="blob-code blob-code-inner js-file-line">  let x = {}</td>
</tr>
<tr>
<td id="file-prorotype-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-prorotype-js-LC2" class="blob-code blob-code-inner js-file-line">  console.log(x.__proto__);</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/1f655703669aa751860afc22e534041a/raw/a7f653502ca84980dde87fc455ae7f4a766c7fb6/Prorotype.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/1f655703669aa751860afc22e534041a#file-prorotype-js" class="Link--inTextBlock"><br />
          Prorotype.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>produces the same output:</p>
<p><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="3067" data-permalink="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/prototype/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/Prototype.png?fit=678%2C223&amp;ssl=1" data-orig-size="678,223" 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="Prototype" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/Prototype.png?fit=678%2C223&amp;ssl=1" class="size-full wp-image-3067 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/Prototype.png?resize=678%2C223&#038;ssl=1" alt="" width="678" height="223" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/Prototype.png?w=678&amp;ssl=1 678w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/Prototype.png?resize=300%2C99&amp;ssl=1 300w" sizes="auto, (max-width: 678px) 100vw, 678px" /></p>
<p>On the top of objects hierarchy, there&#8217;s <span style="color: #ff6600;">Object</span>. Because of that, our <span style="color: #ff6600;">x</span> object is an instance of <span style="color: #ff6600;">Object</span>. That&#8217;s why the prototype of our <span style="color: #ff6600;">x</span> object is actually the <span style="color: #ff6600;">Object.prototype</span>, which contains some common methods we can use (like <span style="color: #ff6600;">toString()</span>).</p>
<p>If we try to access <span style="color: #ff6600;">Object.prototype.__proto__<span style="color: #000000;">, we&#8217;ll see that is contains <em>null</em>.</span></span></p>
<p><strong>Prototypes in JavaScript are mainly used to provide some connection between two or more objects</strong> (like exposing some common methods).</p>
<p>All this &#8220;hierarchy&#8221; of prototypes is used to search for fields and methods of objects: the JS engine first searches in the object itself and if it cannot find particular property, it looks in this object&#8217;s prototype, and then in its prototype until it finds the first matching occurrence. As soon as it reaches <em>null </em>in the <span style="color: #ff6600;">Object.prototype.__proto__ <span style="color: #000000;">it means that the prototypes chain has ended and <em>undefined</em> is returned.</p>
<p></span></span></p>
<p>This kind of prototype inheritance is different than class inheritance, so it&#8217;s often confusing for developers willing to learn JavaScript. Actually, I could write a separate post on this, so if you&#8217;re interested you can read more <a href="https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript" target="_blank" rel="noopener">for instance here</a>.</p>
<h1>10. IIFE</h1>
<p>IIFE is an acronym for <strong>Immediately-Invoked Function Expression</strong>. So what is it and how can it be useful?</p>
<p>Going straight into the code, IIFE can be written as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92879015" 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-iife-js" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-javascript  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="IIFE.js content, created by dsibinski on 10:59PM on November 06, 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="IIFE.js">
<tr>
<td id="file-iife-js-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-iife-js-LC1" class="blob-code blob-code-inner js-file-line">  (function() {</td>
</tr>
<tr>
<td id="file-iife-js-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-iife-js-LC2" class="blob-code blob-code-inner js-file-line">      console.log(&#39;Hey!&#39;);</td>
</tr>
<tr>
<td id="file-iife-js-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-iife-js-LC3" 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/e7441e98355c00a073864e1c65ba5733/raw/5626f46947f63dd141bf0368aa0dd44d811742a3/IIFE.js" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e7441e98355c00a073864e1c65ba5733#file-iife-js" class="Link--inTextBlock"><br />
          IIFE.js<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>As a result of executing such script in a web browser, we&#8217;ll see the following console output:</p>
<blockquote>
<p>Hey!</p>
</blockquote>
<p>How does it work? We neither declared a function&#8217;s name nor called it, right? Actually, we did <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>There are two unusual parts of IIFE implementation: outer parentheses in which we &#8220;wrapped&#8221; our function and &#8220;empty&#8221; parentheses together at its end.</p>
<p>Let&#8217;s start by &#8220;wrapping parentheses&#8221;:</p>
<p><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="3068" data-permalink="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/parentheses_wrapping/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_wrapping.png?fit=315%2C90&amp;ssl=1" data-orig-size="315,90" 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="parentheses_wrapping" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_wrapping.png?fit=315%2C90&amp;ssl=1" class="aligncenter wp-image-3068 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_wrapping.png?resize=315%2C90&#038;ssl=1" alt="" width="315" height="90" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_wrapping.png?w=315&amp;ssl=1 315w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_wrapping.png?resize=300%2C86&amp;ssl=1 300w" sizes="auto, (max-width: 315px) 100vw, 315px" /></p>
<p>Why do we declare them? Because if you don&#8217;t, JavaScript parser will give you an error:</p>
<blockquote>
<p>script.js:1 Uncaught SyntaxError: Unexpected token (</p>
</blockquote>
<p>In such case it thinks that we&#8217;re writing a function declaration and we forgot about providing the function&#8217;s name after the <em>function</em> keyword. Wrapping this into parentheses (&#8230;..) tells the parser that we&#8217;re declaring a <strong>function expression, not a declaration</strong>. After doing this, there are no errors anymore.</p>
<p>The second important part is the &#8220;empty&#8221; parentheses () just after the function expression:</p>
<p><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="3069" data-permalink="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/parentheses_end/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_end.png?fit=315%2C90&amp;ssl=1" data-orig-size="315,90" 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="parentheses_end" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_end.png?fit=315%2C90&amp;ssl=1" class="aligncenter wp-image-3069 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_end.png?resize=315%2C90&#038;ssl=1" alt="" width="315" height="90" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_end.png?w=315&amp;ssl=1 315w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_end.png?resize=300%2C86&amp;ssl=1 300w" sizes="auto, (max-width: 315px) 100vw, 315px" /></p>
<p>As you know, () allows to call the function. That&#8217;s exactly what we do here here &#8211; our function is immediately executed.</p>
<p>Why would we need such construct as IIFE? Developers say that it doesn&#8217;t &#8220;pollute&#8221; the global scope. In effect, we are not leaving the function somewhere after being executed, so no one else can call it accidentally from another place. What&#8217;s more, IIFE is even considered a design pattern.</p>
<p>You should know that such construct exists even only to know what it does seeing it in someone else&#8217;s code. If you want to know more about its use cases, I recommend reading <a href="https://blog.mariusschulz.com/2016/01/19/use-cases-for-javascripts-iifes" target="_blank" rel="noopener">this article</a>.</p>
<h1>Summary</h1>
<p>In this post we&#8217;ve gone through some of the most shocking features of JavaScript language for C# developers. Most of them are confusing for programmers coming from statically-typed and class-based languages and can bring a lot of issues in the beginning of their JavaScript journey.</p>
<p>Just remember that these are the JavaScript&#8217;s language features, not its issues or bugs. That&#8217;s just how it is, but it cannot be said that JavaScript is worse or better than other languages like Java or C#.</p>
<p>The list for sure is not exhaustive, so <span style="text-decoration: underline;">if you have anything to add or correct don&#8217;t hesitate to leave a comment</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>For the end, I&#8217;ll just leave you with the following meme-but-true (thanks <a href="https://twitter.com/YouennBouglouan" target="_blank" rel="noopener">Youenn</a> <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><figure id="attachment_3041" aria-describedby="caption-attachment-3041" style="width: 700px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="3041" data-permalink="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/thanks_javascript/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/thanks_javascript.png?fit=700%2C793&amp;ssl=1" data-orig-size="700,793" 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="thanks_javascript" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/thanks_javascript.png?fit=700%2C793&amp;ssl=1" class="wp-image-3041 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/thanks_javascript.png?resize=700%2C793&#038;ssl=1" alt="" width="700" height="793" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/thanks_javascript.png?w=700&amp;ssl=1 700w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/thanks_javascript.png?resize=265%2C300&amp;ssl=1 265w" sizes="auto, (max-width: 700px) 100vw, 700px" /><figcaption id="caption-attachment-3041" class="wp-caption-text"><a href="http://devhumor.com/media/thanks-brendan-for-giving-us-the-javascript" target="_blank" rel="noopener">Source</a></figcaption></figure></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-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="1778591041" /><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>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/">10 Most Shocking JavaScript Features for C# Developers</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2999</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-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="1778591043" /><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>
<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">  <span class=pl-s1>GCSettings</span><span class=pl-kos>.</span><span class=pl-s1>LargeObjectHeapCompactionMode</span> <span class=pl-c1>=</span> <span class=pl-s1>GCLargeObjectHeapCompactionMode</span><span class=pl-kos>.</span><span class=pl-s1>CompactOnce</span><span class=pl-kos>;</span></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">  <span class=pl-s1>GC</span><span class=pl-kos>.</span><span class=pl-en>Collect</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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-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="1778591043" /><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-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 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="1778591046" /><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="1778591049" /><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="1778591049" /><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>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>SQLite-Net Extensions – one-to-one relationships</title>
		<link>https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/</link>
					<comments>https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 21 May 2017 10:18:15 +0000</pubDate>
				<category><![CDATA[Programming]]></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=2238</guid>

					<description><![CDATA[<p>In this second short post from SQLite-Net Extensions series, we&#8217;re going to see how to create one-to-one relationships using this tiny ORM. One-To-One This is the simplest type of database relationship. An example could be vehicle and registration certificate &#8211; each vehicle has one and only one registration certificate, and one registration certificate is associated&#8230;</p>
<p>The post <a href="https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/">SQLite-Net Extensions – one-to-one relationships</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this second short post from <a href="https://www.codejourney.net/tag/sqlite-net-extensions/" target="_blank" rel="noopener noreferrer">SQLite-Net Extensions</a> series, we&#8217;re going to see how to create one-to-one relationships using this tiny ORM.<br />
<span id="more-2238"></span></p>
<h2>One-To-One</h2>
<p>This is the simplest type of database relationship. An example could be <strong>vehicle</strong> and <strong>registration certificate</strong> &#8211; each vehicle has <em>one and only one</em> registration certificate, and one registration certificate is associated with <em>one and only one</em> vehicle (excluding some extraordinary law rules in other countries that I don&#8217;t know <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>We can model it in two ways:</p>
<ul>
<li>as a <strong>one-way</strong> relationship &#8211; in this case only one of the relationship&#8217;s ends knows about the other one</li>
<li>as a <strong>both-ways</strong> (with inversion) relationship &#8211; both relationship&#8217;s ends know about each other.</li>
</ul>
<h4>One-To-One with no inversion (one-way)</h4>
<p>This kind of relationship looks as follows:</p>
<p><figure id="attachment_2240" aria-describedby="caption-attachment-2240" style="width: 490px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2240" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/1t1_norec/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?fit=550%2C135&amp;ssl=1" data-orig-size="550,135" 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;1495366304&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="1t1_noRec" data-image-description="" data-image-caption="&lt;p&gt;One-To-One &amp;#8211; no &lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?fit=550%2C135&amp;ssl=1" class="wp-image-2240" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?resize=490%2C121&#038;ssl=1" alt="" width="490" height="121" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?resize=300%2C74&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?w=550&amp;ssl=1 550w" sizes="auto, (max-width: 490px) 100vw, 490px" /></a><figcaption id="caption-attachment-2240" class="wp-caption-text">One-To-One &#8211; one-way &#8211; class diagram</figcaption></figure></p>
<p>We use it when we assume it&#8217;s enough that <span style="color: #ff9900;">Vehicle</span> knows about <span style="color: #ff9900;">RegistrationCertificate</span>, but the document doesn&#8217;t necessarily need to know which car/motor it&#8217;s associated with (at least directly).</p>
<p>In the code, we then create two model classes using SQLite-Net Extensions:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47893553" 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-registrationcertificate-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="RegistrationCertificate.cs content, created by dsibinski on 09:36AM on May 21, 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="RegistrationCertificate.cs">
<tr>
<td id="file-registrationcertificate-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-registrationcertificate-cs-LC1" class="blob-code blob-code-inner js-file-line">    [Table(&quot;RegistrationCertificates&quot;)]</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-registrationcertificate-cs-LC2" class="blob-code blob-code-inner js-file-line">    public class RegistrationCertificate</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-registrationcertificate-cs-LC3" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-registrationcertificate-cs-LC4" class="blob-code blob-code-inner js-file-line">        [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-registrationcertificate-cs-LC5" class="blob-code blob-code-inner js-file-line">        public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-registrationcertificate-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-registrationcertificate-cs-LC7" class="blob-code blob-code-inner js-file-line">        public string RegistrationNumber { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-registrationcertificate-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-registrationcertificate-cs-LC9" class="blob-code blob-code-inner js-file-line">        public string VIN { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-registrationcertificate-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-registrationcertificate-cs-LC11" class="blob-code blob-code-inner js-file-line">        public string OwnerData { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-registrationcertificate-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/4970ea35805b27453dc55aa0d5688e5f/raw/f344b75b2d1e98f63d6190c90a8e3221bd5bcb51/RegistrationCertificate.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/4970ea35805b27453dc55aa0d5688e5f#file-registrationcertificate-cs" class="Link--inTextBlock"><br />
          RegistrationCertificate.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47893558" 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-vehicle-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="Vehicle.cs content, created by dsibinski on 09:37AM on May 21, 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="Vehicle.cs">
<tr>
<td id="file-vehicle-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-vehicle-cs-LC1" class="blob-code blob-code-inner js-file-line">    [Table(&quot;Vehicles&quot;)]</td>
</tr>
<tr>
<td id="file-vehicle-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-vehicle-cs-LC2" class="blob-code blob-code-inner js-file-line">    public class Vehicle</td>
</tr>
<tr>
<td id="file-vehicle-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-vehicle-cs-LC3" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-vehicle-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-vehicle-cs-LC4" class="blob-code blob-code-inner js-file-line">        [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-vehicle-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-vehicle-cs-LC5" class="blob-code blob-code-inner js-file-line">        public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-vehicle-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-vehicle-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-vehicle-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-vehicle-cs-LC7" class="blob-code blob-code-inner js-file-line">        public string Brand { get; set; }</td>
</tr>
<tr>
<td id="file-vehicle-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-vehicle-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-vehicle-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-vehicle-cs-LC9" class="blob-code blob-code-inner js-file-line">        public DateTime ProductionDate { get; set; }</td>
</tr>
<tr>
<td id="file-vehicle-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-vehicle-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-vehicle-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-vehicle-cs-LC11" class="blob-code blob-code-inner js-file-line">        public decimal EngineCapacity { get; set; }</td>
</tr>
<tr>
<td id="file-vehicle-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-vehicle-cs-LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-vehicle-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-vehicle-cs-LC13" class="blob-code blob-code-inner js-file-line">        [ForeignKey(typeof(RegistrationCertificate))]</td>
</tr>
<tr>
<td id="file-vehicle-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-vehicle-cs-LC14" class="blob-code blob-code-inner js-file-line">        public int RegistrationCertificateId { get; set; }</td>
</tr>
<tr>
<td id="file-vehicle-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-vehicle-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-vehicle-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-vehicle-cs-LC16" class="blob-code blob-code-inner js-file-line">        [OneToOne]</td>
</tr>
<tr>
<td id="file-vehicle-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-vehicle-cs-LC17" class="blob-code blob-code-inner js-file-line">        public RegistrationCertificate RegistrationCertificate { get; set; }</td>
</tr>
<tr>
<td id="file-vehicle-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-vehicle-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/7ad52df0e33b6a871c1c46f3e0e2dad0/raw/910a48a372f861e3779abb783c966690ad9e020f/Vehicle.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7ad52df0e33b6a871c1c46f3e0e2dad0#file-vehicle-cs" class="Link--inTextBlock"><br />
          Vehicle.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>What&#8217;s interesting here is the <span style="color: #ff9900;">ForeignKeyAttribute</span> defined on <span style="color: #ff9900;">RegistrationCertificateId</span> property. It is &#8211; as its name says &#8211; the foreign key to the primary key of related entity (of type <span style="color: #ff9900;">RegistrationCertificate</span>).</p>
<p>The related entity property itself is decorated with <span style="color: #ff9900;">OneToOneAttribute</span>.</p>
<p>There&#8217;s nothing more we need to do to have this relationship modeled. We can already use it:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47893732" 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-onetoone_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="OneToOne_noInv.cs content, created by dsibinski on 09:49AM on May 21, 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="OneToOne_noInv.cs">
<tr>
<td id="file-onetoone_noinv-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-onetoone_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-onetoone_noinv-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-onetoone_noinv-cs-LC2" class="blob-code blob-code-inner js-file-line">    db.CreateTable&lt;Vehicle&gt;();</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-onetoone_noinv-cs-LC3" class="blob-code blob-code-inner js-file-line">    db.CreateTable&lt;RegistrationCertificate&gt;();</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-onetoone_noinv-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-onetoone_noinv-cs-LC5" class="blob-code blob-code-inner js-file-line">    var vehicle = new Vehicle</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-onetoone_noinv-cs-LC6" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-onetoone_noinv-cs-LC7" class="blob-code blob-code-inner js-file-line">        Brand = &quot;Renault&quot;,</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-onetoone_noinv-cs-LC8" class="blob-code blob-code-inner js-file-line">        EngineCapacity = 1.9m,</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-onetoone_noinv-cs-LC9" class="blob-code blob-code-inner js-file-line">        ProductionDate = new DateTime(2001, 01, 01)</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-onetoone_noinv-cs-LC10" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-onetoone_noinv-cs-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-onetoone_noinv-cs-LC12" class="blob-code blob-code-inner js-file-line">    var certificate = new RegistrationCertificate</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-onetoone_noinv-cs-LC13" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-onetoone_noinv-cs-LC14" class="blob-code blob-code-inner js-file-line">        RegistrationNumber = &quot;AB 12345&quot;,</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-onetoone_noinv-cs-LC15" class="blob-code blob-code-inner js-file-line">        OwnerData = &quot;Dawid Sibiński&quot;,</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-onetoone_noinv-cs-LC16" class="blob-code blob-code-inner js-file-line">        VIN = &quot;1312BS1312ASDSSVVW&quot;</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-onetoone_noinv-cs-LC17" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-onetoone_noinv-cs-LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-onetoone_noinv-cs-LC19" class="blob-code blob-code-inner js-file-line">    db.Insert(vehicle);</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-onetoone_noinv-cs-LC20" class="blob-code blob-code-inner js-file-line">    db.Insert(certificate);</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-onetoone_noinv-cs-LC21" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-onetoone_noinv-cs-LC22" class="blob-code blob-code-inner js-file-line">    vehicle.RegistrationCertificate = certificate;</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-onetoone_noinv-cs-LC23" class="blob-code blob-code-inner js-file-line">    db.UpdateWithChildren(vehicle);</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-onetoone_noinv-cs-LC24" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-onetoone_noinv-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-onetoone_noinv-cs-LC25" class="blob-code blob-code-inner js-file-line">    var vehicleStored = db.GetWithChildren&lt;Vehicle&gt;(vehicle.Id);</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c04bd7030750a87ab3898621612eca03/raw/0430326856944469a47713ff2f61393fa349914e/OneToOne_noInv.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c04bd7030750a87ab3898621612eca03#file-onetoone_noinv-cs" class="Link--inTextBlock"><br />
          OneToOne_noInv.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Nothing special here, right? It looks very similar to what we&#8217;ve seen in the <a href="https://www.codejourney.net/2017/05/sqlite-net-extensions-many-to-many-relationships/" target="_blank" rel="noopener noreferrer">previous post about many-to-many relationships</a>. What&#8217;s interesting for us it that in the end, when <span style="color: #ff9900;">Vehicle</span> object is retrieved from the database using <span style="color: #ff9900;">GetWithChildren</span> method, its <span style="color: #ff9900;">RegistrationCertificate</span> property is filled as well:</p>
<p><figure id="attachment_2242" aria-describedby="caption-attachment-2242" style="width: 521px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2242" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/1t1_norev_debug/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?fit=809%2C334&amp;ssl=1" data-orig-size="809,334" 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="1t1_noRev_debug" data-image-description="" data-image-caption="&lt;p&gt;One-To-One &amp;#8211; filled related entity&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?fit=809%2C334&amp;ssl=1" class="wp-image-2242" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?resize=521%2C215&#038;ssl=1" alt="" width="521" height="215" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?resize=300%2C124&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?resize=768%2C317&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?resize=720%2C297&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?w=809&amp;ssl=1 809w" sizes="auto, (max-width: 521px) 100vw, 521px" /></a><figcaption id="caption-attachment-2242" class="wp-caption-text">One-To-One &#8211; filled related entity</figcaption></figure></p>
<h4>One-To-One with inversion (both-ways)</h4>
<p>This kind of relationship models itself as below:</p>
<p><figure id="attachment_2241" aria-describedby="caption-attachment-2241" style="width: 560px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2241" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/1t1_withrec/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?fit=549%2C135&amp;ssl=1" data-orig-size="549,135" 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;1495366361&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="1t1_withRec" data-image-description="" data-image-caption="&lt;p&gt;One-To-One &amp;#8211; with reversion&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?fit=549%2C135&amp;ssl=1" class="wp-image-2241" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?resize=560%2C138&#038;ssl=1" alt="" width="560" height="138" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?resize=300%2C74&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?w=549&amp;ssl=1 549w" sizes="auto, (max-width: 560px) 100vw, 560px" /></a><figcaption id="caption-attachment-2241" class="wp-caption-text">One-To-One &#8211; with inversion &#8211; class diagram</figcaption></figure></p>
<p>What actually changed on the diagram compared to the relationship with no inversion is that now <span style="color: #ff9900;">RegistrationCertificate</span> has a property of type <span style="color: #ff9900;">Vehicle</span> (in the code &#8211; a reference to <span style="color: #ff9900;">Vehicle</span> related object and a foreign key).</p>
<p>In our case, this is even more &#8220;real&#8221; &#8211; it would be nice if a <span style="color: #ff9900;">Vehicle</span> knows about its <span style="color: #ff9900;">RegistrationCertificate</span>, but also when we look at the certificate we&#8217;d like to see to which car it belongs.</p>
<p>We can now model it in the code. The only thing that changes in the model classes is addition of a reference and foreign key to <span style="color: #ff9900;">Vehicle</span> in <span style="color: #ff9900;">RegistrationCertificate</span> model, so I&#8217;m presenting only this class&#8217;s updated code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47893923" 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-registrationcertificate_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="RegistrationCertificate_withInv.cs content, created by dsibinski on 09:59AM on May 21, 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="RegistrationCertificate_withInv.cs">
<tr>
<td id="file-registrationcertificate_withinv-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-registrationcertificate_withinv-cs-LC1" class="blob-code blob-code-inner js-file-line">    [Table(&quot;RegistrationCertificates&quot;)]</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-registrationcertificate_withinv-cs-LC2" class="blob-code blob-code-inner js-file-line">    public class RegistrationCertificate</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-registrationcertificate_withinv-cs-LC3" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-registrationcertificate_withinv-cs-LC4" class="blob-code blob-code-inner js-file-line">        [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-registrationcertificate_withinv-cs-LC5" class="blob-code blob-code-inner js-file-line">        public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-registrationcertificate_withinv-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-registrationcertificate_withinv-cs-LC7" class="blob-code blob-code-inner js-file-line">        public string RegistrationNumber { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-registrationcertificate_withinv-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-registrationcertificate_withinv-cs-LC9" class="blob-code blob-code-inner js-file-line">        public string VIN { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-registrationcertificate_withinv-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-registrationcertificate_withinv-cs-LC11" class="blob-code blob-code-inner js-file-line">        public string OwnerData { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-registrationcertificate_withinv-cs-LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-registrationcertificate_withinv-cs-LC13" class="blob-code blob-code-inner js-file-line">        // added to have Inversion relationship</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-registrationcertificate_withinv-cs-LC14" class="blob-code blob-code-inner js-file-line">        [ForeignKey(typeof(Vehicle))]</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-registrationcertificate_withinv-cs-LC15" class="blob-code blob-code-inner js-file-line">        public int VehicleId { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-registrationcertificate_withinv-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-registrationcertificate_withinv-cs-LC17" class="blob-code blob-code-inner js-file-line">        [OneToOne]</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-registrationcertificate_withinv-cs-LC18" class="blob-code blob-code-inner js-file-line">        public Vehicle Vehicle { get; set; }</td>
</tr>
<tr>
<td id="file-registrationcertificate_withinv-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-registrationcertificate_withinv-cs-LC19" 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/6b5c7250deff7193c3e127dde2c2a947/raw/1b3f383df9c626044d01225b64bcd94c3004ec9c/RegistrationCertificate_withInv.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/6b5c7250deff7193c3e127dde2c2a947#file-registrationcertificate_withinv-cs" class="Link--inTextBlock"><br />
          RegistrationCertificate_withInv.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>What&#8217;s cool here is that we don&#8217;t need to modify our code for saving entities with relationships into SQLite database. We can simply add the following line at the end:</p>
<pre><pre class="brush: csharp; title: ; notranslate">var certificateStored = db.GetWithChildren&amp;lt;RegistrationCertificate&amp;gt;(certificate.Id);</pre>
<p>and notice that <span style="color: #ff9900;">certificateStored</span> already contains its associated <span style="color: #ff9900;">Vehicle</span> object:</p>
<p><figure id="attachment_2243" aria-describedby="caption-attachment-2243" style="width: 604px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2243" data-permalink="https://www.codejourney.net/sqlite-net-extensions-one-to-one-relationships/1t1_withrev_debug/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?fit=939%2C362&amp;ssl=1" data-orig-size="939,362" 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="1t1_withRev_debug" data-image-description="" data-image-caption="&lt;p&gt;One-To-One &amp;#8211; Vehicle initialized&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?fit=939%2C362&amp;ssl=1" class=" wp-image-2243" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?resize=604%2C234&#038;ssl=1" alt="" width="604" height="234" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?resize=300%2C116&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?resize=768%2C296&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?resize=720%2C278&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?w=939&amp;ssl=1 939w" sizes="auto, (max-width: 604px) 100vw, 604px" /></a><figcaption id="caption-attachment-2243" class="wp-caption-text">One-To-One &#8211; Vehicle initialized</figcaption></figure></p>
<h2>Summary</h2>
<p>In today&#8217;s short post we&#8217;ve seen how to create one-to-one relationship between two entities in SQLite database, using SQLite-Net Extensions ORM. It&#8217;s very easy and doesn&#8217;t require using Entity Framework <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;" /> or writing SQL queries directly in our code.</p>
<p>We&#8217;ve covered two types of one-to-one relationships: one-way and both-ways. The choice between those two depends on the usage and purpose of the relationship we model.</p>
<p>I hope you&#8217;ll find it useful one day <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/sqlite-net-extensions-one-to-one-relationships/">SQLite-Net Extensions – one-to-one 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-one-relationships/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2238</post-id>	</item>
		<item>
		<title>SQLite-Net Extensions &#8211; many-to-many relationships</title>
		<link>https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/</link>
					<comments>https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 18 May 2017 21:23:31 +0000</pubDate>
				<category><![CDATA[Programming]]></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=2218</guid>

					<description><![CDATA[<p>In today&#8217;s post we&#8217;re going to see what is SQLite-Net Extensions ORM and how to use it to create many-to-many relationship in SQLite database. The other types of relationships will be described in separate posts. What is SQLite-Net Extensions ? As you develop any mobile app, sooner than later you need to keep your app&#8217;s data&#8230;</p>
<p>The post <a href="https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/">SQLite-Net Extensions &#8211; many-to-many relationships</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In today&#8217;s post we&#8217;re going to see what is SQLite-Net Extensions ORM and how to use it to create many-to-many relationship in SQLite database. The other types of relationships will be described <a href="https://www.codejourney.net/tag/sqlite-net-extensions/" target="_blank" rel="noopener noreferrer">in separate posts</a>.<br />
<span id="more-2218"></span></p>
<h2>What is SQLite-Net Extensions ?</h2>
<p>As you develop any mobile app, sooner than later you need to keep your app&#8217;s data in some persistent storage. In my <em>MoneyBack </em>project I&#8217;ve chosen<em> </em><a href="https://www.codejourney.net/2017/03/using-sqlite-database-in-xamarin-android/" target="_blank" rel="noopener noreferrer">SQLite database using SQLite.NET library for performing operations on it</a>. This is actually very simple and easy-to-use database framework, but I recently realized I need to model some <strong><a href="https://en.wikipedia.org/wiki/Relation_(database)" target="_blank" rel="noopener noreferrer">relations</a> </strong>in my database.  <a href="https://www.nuget.org/packages/sqlite-net/" target="_blank" rel="noopener noreferrer">SQLite.NET</a> doesn&#8217;t offer any nice utilities to model such relations.</p>
<p>However, if you need to model any relations in your SQLite database, there is a wrapper on SQLite.NET which allows to do that &#8211; it is <strong>SQLite-Net Extensions</strong>. It basically extends the core functionalities of SQLite.NET by adding elements that allow to easily handle relationships, including one-to-one, one-to-many, many-to-one and many-to-many.</p>
<p>In this post we are going to see how to create many-to-many relationship using this library. I needed this kind of relationship to model the connection between Person and Event entities in my app.</p>
<h2>Many-to-many relationship</h2>
<p>Let&#8217;s see many-to-many relationship on an example of two entities: <strong>Person</strong> and <strong>Event</strong>. An event (entity of type <span style="color: #ff9900;">Event</span>) may contain zero or more participants (entities of type <span style="color: #ff9900;">Person</span>) whilst a person may be assigned to zero or more events. This is a typical many-to-many relationship which we are going to set up in our database now.</p>
<h2>Install SQLite-Net Extensions</h2>
<p>If you&#8217;ve previously been using <a href="https://www.nuget.org/packages/sqlite-net/" target="_blank" rel="noopener noreferrer">SQLite.NET</a> in your project &#8211; uninstall it first. I didn&#8217;t do it before starting to use SQLite-Net Extensions and I have many troubles with Visual Studio resolving my references incorrectly. SQLite-Net Extensions is a wrapper for SQLite.NET, so it already contains this library and additionally extends it by adding some extra functionalities for handling relationships.</p>
<p>SQLite-Net Extensions can be installed as a Nuget package into your solution. According to the version you&#8217;d like to use, execute appropriate command in Package Manager Console in Visual Studio:</p>
<ul>
<li>synchronous:
<pre><pre class="brush: csharp; title: ; notranslate">Install-Package SQLiteNetExtensions -Version 1.3.0</pre>
</li>
<li>asynchronous:
<pre><pre class="brush: csharp; title: ; notranslate">Install-Package SQLiteNetExtensions.Async -Version 1.3.0</pre>
</li>
</ul>
<h2>Define model classes</h2>
<p>Next we need to define our <span style="color: #ff9900;">Person</span> and <span style="color: #ff9900;">Event</span> model classes and establish the relationships between them. Below, you can find the code of both classes:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47815728" 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-person_event-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="Person_Event.cs content, created by dsibinski on 08:27PM on May 18, 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="Person_Event.cs">
<tr>
<td id="file-person_event-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-person_event-cs-LC1" class="blob-code blob-code-inner js-file-line">// Person class modelling People table</td>
</tr>
<tr>
<td id="file-person_event-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-person_event-cs-LC2" class="blob-code blob-code-inner js-file-line">[Table(&quot;People&quot;)]</td>
</tr>
<tr>
<td id="file-person_event-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-person_event-cs-LC3" class="blob-code blob-code-inner js-file-line">public class Person</td>
</tr>
<tr>
<td id="file-person_event-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-person_event-cs-LC4" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-person_event-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-person_event-cs-LC5" class="blob-code blob-code-inner js-file-line">    [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-person_event-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-person_event-cs-LC6" class="blob-code blob-code-inner js-file-line">    public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-person_event-cs-LC7" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-person_event-cs-LC8" class="blob-code blob-code-inner js-file-line">    public string Name { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-person_event-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-person_event-cs-LC10" class="blob-code blob-code-inner js-file-line">    public string LastName { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-person_event-cs-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-person_event-cs-LC12" class="blob-code blob-code-inner js-file-line">    public string PhoneNumber { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-person_event-cs-LC13" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-person_event-cs-LC14" class="blob-code blob-code-inner js-file-line">    public string Email { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-person_event-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-person_event-cs-LC16" class="blob-code blob-code-inner js-file-line">    [ManyToMany(typeof(PersonEvent))]</td>
</tr>
<tr>
<td id="file-person_event-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-person_event-cs-LC17" class="blob-code blob-code-inner js-file-line">    public List&lt;Event&gt; Events { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-person_event-cs-LC18" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="file-person_event-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-person_event-cs-LC19" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-person_event-cs-LC20" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-person_event-cs-LC21" class="blob-code blob-code-inner js-file-line">// Event class modelling Events table</td>
</tr>
<tr>
<td id="file-person_event-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-person_event-cs-LC22" class="blob-code blob-code-inner js-file-line">[Table(&quot;Events&quot;)]</td>
</tr>
<tr>
<td id="file-person_event-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-person_event-cs-LC23" class="blob-code blob-code-inner js-file-line">public class Event</td>
</tr>
<tr>
<td id="file-person_event-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-person_event-cs-LC24" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-person_event-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-person_event-cs-LC25" class="blob-code blob-code-inner js-file-line">    [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-person_event-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-person_event-cs-LC26" class="blob-code blob-code-inner js-file-line">    public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-person_event-cs-LC27" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-person_event-cs-LC28" class="blob-code blob-code-inner js-file-line">    public string Name { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
<td id="file-person_event-cs-LC29" class="blob-code blob-code-inner js-file-line">    public DateTime Date { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
<td id="file-person_event-cs-LC30" class="blob-code blob-code-inner js-file-line">    public string Place { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
<td id="file-person_event-cs-LC31" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person_event-cs-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
<td id="file-person_event-cs-LC32" class="blob-code blob-code-inner js-file-line">    [ManyToMany(typeof(PersonEvent))]</td>
</tr>
<tr>
<td id="file-person_event-cs-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
<td id="file-person_event-cs-LC33" class="blob-code blob-code-inner js-file-line">    public List&lt;Person&gt; Participants { get; set; }</td>
</tr>
<tr>
<td id="file-person_event-cs-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
<td id="file-person_event-cs-LC34" 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/1b0f1411d6478c7bebc55a451fbda068/raw/70311b99cece5a78262021d3e63a6034ded89ae2/Person_Event.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/1b0f1411d6478c7bebc55a451fbda068#file-person_event-cs" class="Link--inTextBlock"><br />
          Person_Event.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, the models look almost the same as SQLite.NET db entities, with the following exceptions:</p>
<ul>
<li><span style="color: #ff9900;">ManyToManyAttribute<span style="color: #000000;"> &#8211; o</span></span>n both entities you can notice this attribute defined. On <span style="color: #ff9900;">Person</span> model class I decorate <span style="color: #ff9900;">Events</span> collection with it whereas on <span style="color: #ff9900;">Event</span> model class I decorate <span style="color: #ff9900;">Participants</span> collection with it. Simple as that.</li>
<li><span style="color: #ff9900;">PersonEvent <span style="color: #000000;">&#8211; y</span></span>ou may have noticed that as an argument to <span style="color: #ff9900;">ManyToManyAttribute</span> on both models I passed <span style="color: #ff9900;">PersonEvent</span> type. As you may know, in modelling many-to-many relationships we need an intermediate entity in order to store such kind of relationship in the database tables. The classic example is Student-Course relationship:<br />
<figure id="attachment_2221" aria-describedby="caption-attachment-2221" style="width: 337px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2221" data-permalink="https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/erd-many-to-many-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?fit=469%2C367&amp;ssl=1" data-orig-size="469,367" 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="erd-many-to-many-1" data-image-description="" data-image-caption="&lt;p&gt;Source: smehrozalam&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?fit=469%2C367&amp;ssl=1" class=" wp-image-2221" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?resize=337%2C264&#038;ssl=1" alt="" width="337" height="264" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?resize=300%2C235&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?w=469&amp;ssl=1 469w" sizes="auto, (max-width: 337px) 100vw, 337px" /></a><figcaption id="caption-attachment-2221" class="wp-caption-text">Source: <a href="https://smehrozalam.wordpress.com/2010/06/29/entity-framework-queries-involving-many-to-many-relationship-tables/" target="_blank" rel="noopener noreferrer">smehrozalam</a></figcaption></figure></p>
<p>We also need to define such intermediate entity in our code.</p>
</li>
</ul>
<p>The implementation of <span style="color: #ff9900;">PersonEvent</span> intermediate model class looks as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47816049" 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-personevent-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="PersonEvent.cs content, created by dsibinski on 08:38PM on May 18, 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="PersonEvent.cs">
<tr>
<td id="file-personevent-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-personevent-cs-LC1" class="blob-code blob-code-inner js-file-line">public class PersonEvent</td>
</tr>
<tr>
<td id="file-personevent-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-personevent-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-personevent-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-personevent-cs-LC3" class="blob-code blob-code-inner js-file-line">    [ForeignKey(typeof(Person))]</td>
</tr>
<tr>
<td id="file-personevent-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-personevent-cs-LC4" class="blob-code blob-code-inner js-file-line">    public int PersonId { get; set; }</td>
</tr>
<tr>
<td id="file-personevent-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-personevent-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-personevent-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-personevent-cs-LC6" class="blob-code blob-code-inner js-file-line">    [ForeignKey(typeof(Event))]</td>
</tr>
<tr>
<td id="file-personevent-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-personevent-cs-LC7" class="blob-code blob-code-inner js-file-line">    public int EventId { get; set; }</td>
</tr>
<tr>
<td id="file-personevent-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-personevent-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/33dc1a774b183f4706174a3a656318b9/raw/e8244edf124388dfe058b148fe5bc67d8b71bc1e/PersonEvent.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/33dc1a774b183f4706174a3a656318b9#file-personevent-cs" class="Link--inTextBlock"><br />
          PersonEvent.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Thanks to <span style="color: #ff9900;">PrimaryKey</span> attributes defined on <span style="color: #ff9900;">Person</span> and <span style="color: #ff9900;">Event</span> entities the ORM will be able to determine to which primary keys the foreign keys in this intermediate table relate.</p>
<p>In the <span style="color: #ff9900;">ManyToManyAttribute</span>, except the type of intermediate entity, you can set <span style="color: #ff9900;">CascadeOperations</span>, which specifies how the cascading should be handled when working with the entities (e.g. if cascade delete operation should be performed when one of the relationship&#8217;s sides is removed).</p>
<h2>Inserting and reading data</h2>
<p>As soon as our model classes are defined, we can write and read the data with many-to-many relationships. The following code presents a simple way to create a new person and assign it to an event:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist47816466" 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-savingpersonevent-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="SavingPersonEvent.cs content, created by dsibinski on 08:47PM on May 18, 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="SavingPersonEvent.cs">
<tr>
<td id="file-savingpersonevent-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-savingpersonevent-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-savingpersonevent-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-savingpersonevent-cs-LC2" class="blob-code blob-code-inner js-file-line">db.CreateTable&lt;Person&gt;();</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-savingpersonevent-cs-LC3" class="blob-code blob-code-inner js-file-line">db.CreateTable&lt;Event&gt;();</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-savingpersonevent-cs-LC4" class="blob-code blob-code-inner js-file-line">db.CreateTable&lt;PersonEvent&gt;();</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-savingpersonevent-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-savingpersonevent-cs-LC6" class="blob-code blob-code-inner js-file-line">var event1 = new Event</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-savingpersonevent-cs-LC7" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-savingpersonevent-cs-LC8" class="blob-code blob-code-inner js-file-line">    Name = &quot;Volleyball&quot;,</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-savingpersonevent-cs-LC9" class="blob-code blob-code-inner js-file-line">    Date = new DateTime(2017, 06, 18),</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-savingpersonevent-cs-LC10" class="blob-code blob-code-inner js-file-line">    Place = &quot;Sports hall&quot;</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-savingpersonevent-cs-LC11" class="blob-code blob-code-inner js-file-line">};</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-savingpersonevent-cs-LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-savingpersonevent-cs-LC13" class="blob-code blob-code-inner js-file-line">var person1 = new Person</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-savingpersonevent-cs-LC14" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-savingpersonevent-cs-LC15" class="blob-code blob-code-inner js-file-line">    Name = &quot;A&quot;,</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-savingpersonevent-cs-LC16" class="blob-code blob-code-inner js-file-line">    LastName = &quot;B&quot;,</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-savingpersonevent-cs-LC17" class="blob-code blob-code-inner js-file-line">    PhoneNumber = &quot;123456789&quot;</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-savingpersonevent-cs-LC18" class="blob-code blob-code-inner js-file-line">};</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-savingpersonevent-cs-LC19" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-savingpersonevent-cs-LC20" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-savingpersonevent-cs-LC21" class="blob-code blob-code-inner js-file-line">db.Insert(person1);</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-savingpersonevent-cs-LC22" class="blob-code blob-code-inner js-file-line">db.Insert(event1);</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-savingpersonevent-cs-LC23" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-savingpersonevent-cs-LC24" class="blob-code blob-code-inner js-file-line">person1.Events = new List&lt;Event&gt; { event1 };</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-savingpersonevent-cs-LC25" class="blob-code blob-code-inner js-file-line">db.UpdateWithChildren(person1);</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-savingpersonevent-cs-LC26" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-savingpersonevent-cs-LC27" class="blob-code blob-code-inner js-file-line">var personStored = db.GetWithChildren&lt;Person&gt;(person1.Id);</td>
</tr>
<tr>
<td id="file-savingpersonevent-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-savingpersonevent-cs-LC28" class="blob-code blob-code-inner js-file-line">var eventStored = db.GetWithChildren&lt;Event&gt;(event1.Id);</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/4b8566aba0d8280aa5117de3f1ce70fc/raw/5fc7f3d27f4313031c31cb40810e76a0e895b053/SavingPersonEvent.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/4b8566aba0d8280aa5117de3f1ce70fc#file-savingpersonevent-cs" class="Link--inTextBlock"><br />
          SavingPersonEvent.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Lines 1-4 contain the database initialization (<span style="color: #ff9900;">Constants.DbFilePath</span> just returns an Android path of SQLite database file) and creation of all 3 tables in the database.</p>
<p>Lines 6-18 are simply the creation of <span style="color: #ff9900;">Person</span> and <span style="color: #ff9900;">Event</span> objects, filled with most basic details.</p>
<p>In lines 21 and 22 we firstly save our <span style="color: #ff9900;">person1</span> and <span style="color: #ff9900;">event1</span> entities separately, because in order to establish the relationships we need the primary keys of those entities, that are assigned by the database while saving. This can be also simplified by using recursive operations &#8211; more details in the <a href="https://bitbucket.org/twincoders/sqlite-net-extensions/" target="_blank" rel="noopener noreferrer">official documentation of the ORM</a>.</p>
<p>After that, we assign just created person to the event (line 24) and then the most rocket-science part comes:</p>
<pre><pre class="brush: csharp; title: ; notranslate">db.UpdateWithChildren(person1);</pre>
<p>This method does the write magic &#8211; it updates the person with all its children &#8211; so in our case, the <span style="color: #ff9900;">Events</span> collection. It will make the relationship established.</p>
<p>In order to prove it, in lines 27 and 28 we can check if the relationship collections are populated with children in both entities by calling <span style="color: #ff9900;">GetWithChildren</span> extension methods:</p>
<p><figure id="attachment_2231" aria-describedby="caption-attachment-2231" style="width: 571px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2231" data-permalink="https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/personcontainsevents-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?fit=814%2C321&amp;ssl=1" data-orig-size="814,321" 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="personContainsEvents" data-image-description="" data-image-caption="&lt;p&gt;Person containing Events&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?fit=814%2C321&amp;ssl=1" class="wp-image-2231 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?resize=571%2C225&#038;ssl=1" alt="" width="571" height="225" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?w=814&amp;ssl=1 814w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?resize=300%2C118&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?resize=768%2C303&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?resize=720%2C284&amp;ssl=1 720w" sizes="auto, (max-width: 571px) 100vw, 571px" /></a><figcaption id="caption-attachment-2231" class="wp-caption-text">Person containing Events</figcaption></figure> <figure id="attachment_2228" aria-describedby="caption-attachment-2228" style="width: 573px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2228" data-permalink="https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/eventcontainsparticipants-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?fit=932%2C390&amp;ssl=1" data-orig-size="932,390" 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="eventContainsParticipants" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?fit=932%2C390&amp;ssl=1" class="wp-image-2228 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?resize=573%2C240&#038;ssl=1" alt="" width="573" height="240" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?w=932&amp;ssl=1 932w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?resize=300%2C126&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?resize=768%2C321&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?resize=720%2C301&amp;ssl=1 720w" sizes="auto, (max-width: 573px) 100vw, 573px" /></a><figcaption id="caption-attachment-2228" class="wp-caption-text">Event containing Participants</figcaption></figure></p>
<p>That&#8217;s how SQLite-Net Extensions ORM works. It doesn&#8217;t provide any lazy-loading of related entities &#8211; it just adds/retrieves to/from the database exactly what you tell it to. The limitation here is that if you access <span style="color: #ff9900;">Person.Events</span> collection you can see the events this person is in relation with, but if you access <span style="color: #ff9900;">Person.Events[0]</span> you will not see all people registered for this event.</p>
<h2>Summary</h2>
<p>SQLite-Net Extensions is an ORM, which is a wrapper for classic SQLite.NET library. It adds the extension methods/attributes to handle relationships in SQLite database. It doesn&#8217;t provide any lazy-loading mechanism, instead exposing methods for getting/saving entities along with their children (related entities). It&#8217;s lightweight and rather easy to implement, so for small solutions like mobile apps I totally prefer it to writing and maintaining SQL queries directly in C# in order to handle relationships.</p>
<p>In the next posts from the <a href="https://www.codejourney.net/tag/sqlite-net-extensions/" target="_blank" rel="noopener noreferrer">series about SQLite-Net Extensions ORM</a>, I will present to you the other types of relationships this ORM offers. Stay tuned <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>The post <a href="https://www.codejourney.net/sqlite-net-extensions-many-to-many-relationships/">SQLite-Net Extensions &#8211; many-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-many-to-many-relationships/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2218</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>Android Apps Localization</title>
		<link>https://www.codejourney.net/android-apps-localization/</link>
					<comments>https://www.codejourney.net/android-apps-localization/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 19 Apr 2017 20:48:55 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=1803</guid>

					<description><![CDATA[<p>Hello everyone 🙂 As you might have noticed, I&#8217;ve recently decided to take a longer break in DSP competition. Few things to do, Easter in the meantime&#8230; but of course I didn&#8217;t give up and today I&#8217;m back 😉 In this post I&#8217;d like to show you how do we localize Android apps. Let&#8217;s see! What&#8230;</p>
<p>The post <a href="https://www.codejourney.net/android-apps-localization/">Android Apps Localization</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Hello everyone 🙂</p>
<p>As you might have noticed, I&#8217;ve recently decided to take a longer break in DSP competition. Few things to do, Easter in the meantime&#8230; but of course I didn&#8217;t give up and today I&#8217;m back 😉</p>
<p>In this post I&#8217;d like to show you how do we localize Android apps. Let&#8217;s see!<br />
<span id="more-1803"></span></p>
<h2>What is localization ?</h2>
<p>Generally, <strong>localization </strong>is a <em>process of adapting the product or application to specific markets by adjusting its language and cultural resources accordingly</em>.</p>
<p>People often think that localization is only a process of translating documentation and user interface into multiple languages, but in fact it may concern many other not less important topics, e.g. formats of numeric values or dates, currencies, numbers comparison/sorting methods, symbols, national flags or even country-specific law requirements.</p>
<p>Android supports app&#8217;s resources localization in pretty easy way. We can quite conveniently provide different versions of strings, images and layouts used in our application for different languages/regions. Let&#8217;s take a look at the basics of Android app&#8217;s localization.</p>
<h2>Android localization basics</h2>
<p>In every Android application, localization is based on the language user has set on his/her device. The language can be changed in <strong>Settings -&gt; Language &amp; input</strong>. Changing the language in this place affects both user interface&#8217;s language and region-specific settings (e.g. dates formats).</p>
<p>To retrieve the current <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html" target="_blank" rel="noopener">locale</a> (constant/object representing selected language) in code the following statement can be used:</p>
<pre><pre class="brush: csharp; title: ; notranslate">var currentLang = Resources.Configuration.Locale;</pre>
<p>In case user has Polish language set on his/her phone, <span style="color: #ff9900;">currentLang</span> variable would contain &#8220;pl_PL&#8221; locale symbol. For the full list of locales symbols, see <a href="http://www.oracle.com/technetwork/java/javase/locales-137662.html" target="_blank" rel="noopener">for example this list.</a></p>
<p>Basically, everything that is placed under <em>Resources</em> folder in Android solution can be localized. All of you probably have <em>values</em> folder in <em>Resources</em>, which contains <em>Strings.xml</em> file. We&#8217;ll see more details about this file in a while, but to present the ease of localization to you, it&#8217;s enough to create another folder under <em>Resources</em> called e.g. <em>values-pl</em>, which makes retrieving strings from <em>Strings.xml</em> file located in this folder on devices with language set to Polish. Simple as that. The same can be done with every type of resource. It means we can create totally different layouts of our Activities or use different images (e.g. countries&#8217; flags) depending on user&#8217;s device&#8217;s language.</p>
<h2>Strings localization</h2>
<h4>Strings.xml file</h4>
<p>To-be-localized strings (BTW, I think that we should do it straightaway with all strings we use in our app) should be put in <em>values</em>/<em>Strings.xml</em> file, which has the following structure:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46853585" 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-strings-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="Strings.xml content, created by dsibinski on 06:55PM on April 19, 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="Strings.xml">
<tr>
<td id="file-strings-xml-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-strings-xml-LC1" class="blob-code blob-code-inner js-file-line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-strings-xml-LC2" class="blob-code blob-code-inner js-file-line">&lt;resources&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-strings-xml-LC3" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;ApplicationName&quot;&gt;MoneyBack&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-strings-xml-LC4" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titleMenu&quot;&gt;Menu:&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-strings-xml-LC5" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;btnPeople&quot;&gt;People management&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-strings-xml-LC6" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titleName&quot;&gt;Name&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-strings-xml-LC7" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titleLastName&quot;&gt;Last name&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-strings-xml-LC8" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titlePhoneNumber&quot;&gt;Phone number&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-strings-xml-LC9" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;btnSavePerson&quot;&gt;Save person&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-strings-xml-LC10" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;btnPeopleList&quot;&gt;List of people&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-strings-xml-LC11" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;peopleListTitle&quot;&gt;List of people&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-strings-xml-LC12" class="blob-code blob-code-inner js-file-line">&lt;/resources&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/a0ae912d93e038ddf4b958666413edca/raw/420e073b031ec34f5a0c6b2fe1f47a448054d065/Strings.xml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/a0ae912d93e038ddf4b958666413edca#file-strings-xml" class="Link--inTextBlock"><br />
          Strings.xml<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>The file is built in accordance with standard XML rules. The <em>name</em> represents <strong>Android resource ID</strong> (cannot contain any spaces or dashes) to which we will refer from code and other places in order to retrieve the <strong>value</strong> of this resource, which is placed between &#8220;&gt;&#8221; and &#8220;&lt;&#8221; characters.</p>
<p>For instance, first resource from above-pasted <em>Strings.xml</em> has <em>name</em> = &#8220;ApplicationName&#8221; and <em>value</em> = &#8220;MoneyBack&#8221;.</p>
<p>As mentioned in the previous paragraph, I also created <em>Strings.xml</em> file in <em>values-pl</em> folder, containing the same resources&#8217; Polish translations. The contents of <em>values-pl/Strings.xml</em> file:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46854312" 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-strings-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="Strings.xml content, created by dsibinski on 07:18PM on April 19, 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="Strings.xml">
<tr>
<td id="file-strings-xml-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-strings-xml-LC1" class="blob-code blob-code-inner js-file-line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-strings-xml-LC2" class="blob-code blob-code-inner js-file-line">&lt;resources&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-strings-xml-LC3" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;ApplicationName&quot;&gt;MoneyBack&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-strings-xml-LC4" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titleMenu&quot;&gt;Menu:&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-strings-xml-LC5" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;btnPeople&quot;&gt;Zarządzaj osobami&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-strings-xml-LC6" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titleName&quot;&gt;Imię&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-strings-xml-LC7" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titleLastName&quot;&gt;Nazwisko&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-strings-xml-LC8" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;titlePhoneNumber&quot;&gt;Numer telefonu&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-strings-xml-LC9" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;btnSavePerson&quot;&gt;Zapisz osobę&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-strings-xml-LC10" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;btnPeopleList&quot;&gt;Lista osób&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-strings-xml-LC11" class="blob-code blob-code-inner js-file-line">    &lt;string name=&quot;peopleListTitle&quot;&gt;Lista osób&lt;/string&gt;</td>
</tr>
<tr>
<td id="file-strings-xml-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-strings-xml-LC12" class="blob-code blob-code-inner js-file-line">&lt;/resources&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/1376460c699c37b6c72a5c8d911e2c66/raw/0fad55e5233c5f3704011acbb74cb60c6231e3a2/Strings.xml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/1376460c699c37b6c72a5c8d911e2c66#file-strings-xml" class="Link--inTextBlock"><br />
          Strings.xml<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<h4>Usage in layout files</h4>
<p>In our Activities&#8217; layout files (AXML) we can retrieve resources&#8217; values by using <em>@string/id</em> syntax. For example, <span style="color: #ff9900;">TextView</span>&#8216;s text can be set in the following way:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46854495" 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 07:25PM on April 19, 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;TextView</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:text=&quot;@string/titleMenu&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:id=&quot;@+id/titleMenu&quot; /&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/862fadb2f8d1ef158961aa9fa7f1f009/raw/5d1b641f8b95fd886ec261b33f9381424e3a3038/Main.axml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/862fadb2f8d1ef158961aa9fa7f1f009#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>It can be used exactly the same way in the UI designer in Visual Studio.</p>
<h4>Usage directly in code</h4>
<p>In the code we can retrieve values of particular resources using <span style="color: #ff9900;">Resources.GetText</span> method giving it selected resource&#8217;s id as <span style="color: #ff9900;">Resource.String</span> class&#8217;s property:</p>
<pre><pre class="brush: csharp; title: ; notranslate">string titleMenuText = Resources.GetText(Resource.String.titleMenu);</pre>
<p>With all strings translated, I can see UI of <em>MoneyBack</em> translated when my device&#8217;s language is set to Polish:</p>
<p>
<a href='https://www.codejourney.net/android-apps-localization/moneyback_pl/'><img loading="lazy" decoding="async" width="169" height="300" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?fit=169%2C300&amp;ssl=1" class="attachment-medium size-medium" alt="" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?w=1080&amp;ssl=1 1080w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?resize=720%2C1280&amp;ssl=1 720w" sizes="auto, (max-width: 169px) 100vw, 169px" data-attachment-id="1927" data-permalink="https://www.codejourney.net/android-apps-localization/moneyback_pl/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.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_PL" data-image-description="" data-image-caption="&lt;p&gt;MoneyBack &amp;#8211; PL&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?fit=576%2C1024&amp;ssl=1" /></a>
<a href='https://www.codejourney.net/android-apps-localization/moneyback_en/'><img loading="lazy" decoding="async" width="169" height="300" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?fit=169%2C300&amp;ssl=1" class="attachment-medium size-medium" alt="" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?w=1080&amp;ssl=1 1080w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?resize=720%2C1280&amp;ssl=1 720w" sizes="auto, (max-width: 169px) 100vw, 169px" data-attachment-id="1926" data-permalink="https://www.codejourney.net/android-apps-localization/moneyback_en/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.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_EN" data-image-description="" data-image-caption="&lt;p&gt;MoneyBack &amp;#8211; EN&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?fit=576%2C1024&amp;ssl=1" /></a>
</p>
<h4>Quantity strings</h4>
<p>Very interesting concept are so called <strong>quantity strings</strong>. It allows to define differently formatted strings depending on a number of some elements determined at runtime. For instance, on the list of people we could have the following strings displayed depending on the number of people:</p>
<p>&#8220;There is 1 person in your database.&#8221;</p>
<p>&#8220;There are 2 people in your database.&#8221;</p>
<p>To declare such kind of quantity string, we&#8217;d add to <em>Strings.xml</em> the following section:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46854777" 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-strings_plurals-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="Strings_plurals.xml content, created by dsibinski on 07:35PM on April 19, 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="Strings_plurals.xml">
<tr>
<td id="file-strings_plurals-xml-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-strings_plurals-xml-LC1" class="blob-code blob-code-inner js-file-line">&lt;<span class="pl-ent">plurals</span> <span class="pl-e">name</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>numberOfPeople<span class="pl-pds">&quot;</span></span>&gt;</td>
</tr>
<tr>
<td id="file-strings_plurals-xml-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-strings_plurals-xml-LC2" class="blob-code blob-code-inner js-file-line">         &lt;<span class="pl-ent">item</span> <span class="pl-e">quantity</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>one<span class="pl-pds">&quot;</span></span>&gt;There is %d person in your database.&lt;/<span class="pl-ent">item</span>&gt;</td>
</tr>
<tr>
<td id="file-strings_plurals-xml-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-strings_plurals-xml-LC3" class="blob-code blob-code-inner js-file-line">         &lt;<span class="pl-ent">item</span> <span class="pl-e">quantity</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>other<span class="pl-pds">&quot;</span></span>&gt;There are %d people in your database..&lt;/<span class="pl-ent">item</span>&gt;</td>
</tr>
<tr>
<td id="file-strings_plurals-xml-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-strings_plurals-xml-LC4" class="blob-code blob-code-inner js-file-line"> &lt;/<span class="pl-ent">plurals</span>&gt;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/242f23517ee05b52f6ec365dd06e9ef6/raw/88b97726600cff4fc890821351ef1da81f346a72/Strings_plurals.xml" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/242f23517ee05b52f6ec365dd06e9ef6#file-strings_plurals-xml" class="Link--inTextBlock"><br />
          Strings_plurals.xml<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>To illustrate: in order to retrieve and format appropriate string depending on value stored in <span style="color: #ff9900;">numPeople</span> variable, the following code might be used:</p>
<pre><pre class="brush: csharp; title: ; notranslate">var text = Resources.GetQuantityString(Resource.Plurals.numberOfPeople, numPeople, numPeople);</pre>
<p>Second parameter passed is used to determine <strong>which</strong> string (plural) to use, and third parameter is the <strong>actual value</strong> passed to the final string (in the place of <em>%d</em> in that case).</p>
<p>The <em>quantity</em> of each plural can contain one of the following values:</p>
<ul>
<li>zero</li>
<li>one</li>
<li>two</li>
<li>few</li>
<li>many</li>
<li>other</li>
</ul>
<p>More details can be found <a href="https://developer.android.com/guide/topics/resources/string-resource.html#Plurals" target="_blank" rel="noopener">here</a>.</p>
<h4>Application&#8217;s/Activity&#8217;s name</h4>
<p>We can also localize the name of our app, by using string resource in the <span style="color: #ff9900;">ActivityAttribute</span> defined on <span style="color: #ff9900;">MainActivity</span>:</p>
<pre><pre class="brush: csharp; title: ; notranslate">&#x5B;Activity(Label = &quot;@string/ApplicationName&quot;, MainLauncher = true, Icon = &quot;@drawable/icon&quot;)]</pre>
<p>The same can be done for any of our app&#8217;s activities. However, be careful here if you are referencing your main Android project from another one (e.g. from tests project) &#8211; I&#8217;ve experienced really annoying issue with that (more details below).</p>
<h4>Other resources</h4>
<p>As we already said, not only strings can be localized. You can localize any kind of resources placed within <em>Resources</em> folder, for example images or data files.</p>
<h2>The file “obj\Debug\android\bin\packaged_resources” does not exist</h2>
<p>Two weeks ago, when I finally decided to take a break in publishing DSP posts, I wanted to work on <em>MoneyBack</em> a bit, however I encountered very frustrating issue, which I even described in <a href="http://stackoverflow.com/questions/43294345/visual-studio-2017-xamarin-the-file-obj-debug-android-bin-packaged-resource" target="_blank" rel="noopener">this StackOverflow post</a>. I&#8217;ve been fighting with that problem for few days and I still actually don&#8217;t know the real cause of the issue.</p>
<p>Basically, when I used resource string on my <span style="color: #ff9900;">PeopleListActivity</span> in order to translate its title:</p>
<pre><pre class="brush: csharp; title: ; notranslate">&#x5B;Activity(Label = &quot;@string/peopleListTitle&quot;)]</pre>
<p>I couldn&#8217;t build my <strong>MoneyBack.Android.Tests </strong>(yes, different project!) project. I was getting the following build error message:</p>
<p><figure id="attachment_1955" aria-describedby="caption-attachment-1955" style="width: 963px" class="wp-caption alignnone"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1955" data-permalink="https://www.codejourney.net/android-apps-localization/resourcenotfound/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?fit=963%2C163&amp;ssl=1" data-orig-size="963,163" 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;1492631799&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="ResourceNotFound" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?fit=963%2C163&amp;ssl=1" class=" size-full wp-image-1955 alignnone" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?resize=963%2C163&#038;ssl=1" alt="ResourceNotFound.JPG" width="963" height="163" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?w=963&amp;ssl=1 963w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?resize=300%2C51&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?resize=768%2C130&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?resize=720%2C122&amp;ssl=1 720w" sizes="auto, (max-width: 963px) 100vw, 963px" /><figcaption id="caption-attachment-1955" class="wp-caption-text">Error during building Android tests project</figcaption></figure></p>
<p>I explored all existing forums threads on this topic and couldn&#8217;t resolve this issue. Finally, by setting build output verbosity to <code>Diagnostic</code> in <em>Tools -&gt; Options -&gt; Projects and Solutions -&gt; Build and Run </em>I was able to see the detailed error my build process is giving. It was telling me that <em>@string/peopleListTitle </em>doesn&#8217;t exist (or something similar). So when I changed the <span style="color: #ff9900;">Label</span>&#8216;s value in <span style="color: #ff9900;">ActivityAttribute</span> to use a string directly (not taken as a resource), it worked fine and the build passed.</p>
<p>Today I tried once more to use resource string, obviously getting the same error message. Then I realized that my <em>MoneyBack.Android.Tests</em> project is referencing  <em>MoneyBack</em> project in which I define those somehow missing strings:</p>
<p><figure id="attachment_1965" aria-describedby="caption-attachment-1965" style="width: 266px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1965" data-permalink="https://www.codejourney.net/android-apps-localization/resourcenotfound_test_reference/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound_Test_Reference.jpg?fit=384%2C426&amp;ssl=1" data-orig-size="384,426" 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;1492631847&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="ResourceNotFound_Test_Reference" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound_Test_Reference.jpg?fit=384%2C426&amp;ssl=1" class=" wp-image-1965 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound_Test_Reference.jpg?resize=266%2C295&#038;ssl=1" alt="ResourceNotFound_Test_Reference.JPG" width="266" height="295" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound_Test_Reference.jpg?w=384&amp;ssl=1 384w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound_Test_Reference.jpg?resize=270%2C300&amp;ssl=1 270w" sizes="auto, (max-width: 266px) 100vw, 266px" /><figcaption id="caption-attachment-1965" class="wp-caption-text">Tests project referencing the main one</figcaption></figure></p>
<p>so I removed that reference (commenting out my unit tests which use <em>MoneyBack</em>&#8216;s logic) and the build worked fine. Apparently when trying to build tests project, which references the main one, in which my strings are defined, <strong>it somehow needs those strings resources to be present in tests project&#8217;s output directory.</strong> I have no idea why, because I&#8217;m not directly using those strings resources in my tests project.</p>
<p>Then I added the reference back and in <em>MoneyBack.Android.Tests</em> project I just created <em>values</em> folder and copy-pasted <em>Strings.xml</em> file to it from the <em>MoneyBack</em> project:</p>
<p><figure id="attachment_1978" aria-describedby="caption-attachment-1978" style="width: 1166px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1978" data-permalink="https://www.codejourney.net/android-apps-localization/resources_strings_copied/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?fit=1166%2C330&amp;ssl=1" data-orig-size="1166,330" 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;1492632228&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="Resources_Strings_Copied" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?fit=1024%2C290&amp;ssl=1" class="aligncenter size-full wp-image-1978" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?resize=1140%2C323&#038;ssl=1" alt="Resources_Strings_Copied.JPG" width="1140" height="323" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?w=1166&amp;ssl=1 1166w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?resize=300%2C85&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?resize=768%2C217&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?resize=1024%2C290&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?resize=720%2C204&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /><figcaption id="caption-attachment-1978" class="wp-caption-text">Strings.xml copied into test project</figcaption></figure></p>
<p>and it builds OK!</p>
<p><span style="text-decoration: underline;"><strong>Does any of you have some idea why it may happen?</strong></span> <span style="text-decoration: underline;"><strong>If you have a clue, you can answer here or even <a href="http://stackoverflow.com/questions/43294345/visual-studio-2017-xamarin-the-file-obj-debug-android-bin-packaged-resource" target="_blank" rel="noopener">on SO.</a></p>
<p></strong></span></p>
<p>For me it seems like a bug in the build process. I wanted to share it with you, because I wasted so much time because of this issue and maybe some of you will also find it useful.</p>
<p>BTW, I really recommend using Diagnostic verbosity of the build output for debugging such issues.</p>
<h2>Summary</h2>
<p>We&#8217;ve seen how Android application can be easily localized. I really recommend to put all strings visible for the end user from the beginning in <em>Strings.xml</em> file. Thanks to that, in case our application needs to be <strong>localized</strong>, we can even hire/ask some foreign languages&#8217; interpreters to create country-specific <em>values</em> folder and translate strings resources conveniently. This is even very common in mobile apps communities, that people who are non-technical can contribute to the project by translating the application into their own language.</p>
<p>I hope I won&#8217;t meet any other issues like the one I described today on my further DSP way 🙂 It would allow me to write more stuff here and hopefully implement some usable app finally! Keep your fingers crossed 🙂</p>
<p>PS: If I already mentioned taking breaks in DSP competition, I will also take one more during the first week of May (1-5.05.2017). In case anyone cares 😉</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/android-apps-localization/">Android Apps Localization</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/android-apps-localization/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1803</post-id>	</item>
		<item>
		<title>Xamarin &#8211; Android Intents</title>
		<link>https://www.codejourney.net/xamarin-android-intents/</link>
					<comments>https://www.codejourney.net/xamarin-android-intents/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 01 Apr 2017 10:19:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=1499</guid>

					<description><![CDATA[<p>We&#8217;ve already seen what are Activities, the most basic pieces of every Android app and today&#8217;s topic is associated with it. We&#8217;re going to see how to communicate between Activities (or Application Blocks) using Intents. Android Application Blocks Android apps are composed of Application Blocks, which are special kind of Android classes consisting several elements bundled together,&#8230;</p>
<p>The post <a href="https://www.codejourney.net/xamarin-android-intents/">Xamarin &#8211; Android Intents</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We&#8217;ve already seen what are <a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener">Activities</a>, the most basic pieces of every Android app and today&#8217;s topic is associated with it. We&#8217;re going to see how to communicate between Activities (or <em>Application Blocks</em>) using <em>Intents</em>.<br />
<span id="more-1499"></span></p>
<h2>Android Application Blocks</h2>
<p>Android apps are composed of <em>Application Blocks</em>, which are special kind of Android classes consisting several elements bundled together, including:</p>
<ul>
<li><a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener">Activities</a></li>
<li><a href="https://developer.xamarin.com/guides/android/application_fundamentals/services/" target="_blank" rel="noopener">Services</a></li>
<li>Resources (images, themes, classes)</li>
</ul>
<p>Everything that comes in such <em>package</em> is coordinated by <em>AndroidManifest.XML</em> file. Especially, in this XML file (or by using various attributes on Activity class) it&#8217;s possible to <em>register</em> our <em>Application Block</em> to be &#8220;callable&#8221; by the others.</p>
<p>We&#8217;ll see more details in a while, but generally your app block is &#8220;callable&#8221; when it can be used by the other apps &#8211; probably you&#8217;ve already seen Application Chooser screen on your Android phone, e.g. when you wanted to open downloaded movie and the system asked you which video player you want to use. The same can be done with your own app &#8211; if you&#8217;re developing a dialer app, you can register it to be callable for <em><a href="https://developer.android.com/reference/android/content/Intent.html#ACTION_DIAL" target="_blank" rel="noopener">ACTION_DIAL</a> </em>Activity Action. Then, as soon as any other app uses <em>Intent</em> to make a phone call (which we&#8217;ll see in this post), Application Chooser appears and your app will be one of the possible ones to use for making this phone call.</p>
<h2>What is an Intent ?</h2>
<p>Android system is designed to be <em>loosely-coupled</em>. Moreover, there is a <em>principle of least privilege</em> introduced in system&#8217;s architecture. It means that each app has access only to <em>Blocks</em> which it requires to work. Different <em>Blocks</em> don&#8217;t know much about each other (even if defined within the same application). Here&#8217;s where an<em> </em><em>Intent</em> comes into play. <em><strong>Application Blocks</strong></em><strong> use </strong><strong><em>Intents</em></strong><strong> to asynchronously communicate with each other.</p>
<p></strong></p>
<p>In general, you can think of an <em>Intent </em>literally &#8211; <strong>it&#8217;s the <em>intent</em> (or a <em>will</em>) to do something</strong>. By sending <em>Intents</em> between different components, we can coordinate complex actions such as launching email app to send a message, using Location for obtaining user&#8217;s coordinates or navigating between application&#8217;s screens.</p>
<p>For me, we can think of <em>Intents</em> and their usage from two perspectives:</p>
<ol>
<li><strong><em>Intent</em> as an</strong> <span style="text-decoration: underline;"><strong>intent</strong></span><strong> </strong>&#8211; a will to do something. In this case, you use <em>Intent</em> to execute <em>some</em> action. When creating a new <em>Intent</em> you need to tell it <em>what</em> you want to do and give it necessary <em>parameters</em> for such operation (e.g. for <em>send email</em> action, you need to provide <em>email address </em>parameter)</li>
<li><strong><em>Intent</em> as a</strong> <span style="text-decoration: underline;"><strong>message </strong></span>&#8211; bidirectional information having <em>sender</em>, <em>recipient </em>and potentially some <em>content</em>. This can be for instance navigating to a new screen (Activity), where sender is the original Activity, recipient is the destination Activity to be opened and the content may consist some parameters to pass between two screens.</li>
</ol>
<p>We&#8217;ll now see those two approaches in details.</p>
<h2>Intent as an intent</h2>
<p>In order to trigger another (external) action, e.g. camera recording or email sending, we can create an <em>Intent</em> and start a new Activity. Let&#8217;s see it by the example I implemented in <em>MoneyBack</em> &#8211; I added an additional <em>ListActivity</em> (<span style="color: #ff9900;">PeopleListActivity</span> class) which is the list of people added to app&#8217;s database. When a person on the list is clicked, I create an <em>Intent</em> in order to call his/her phone number as the following code presents:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46270777" 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-peoplelistactivity_clicking-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="PeopleListActivity_clicking.cs content, created by dsibinski on 09:03AM on April 01, 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="PeopleListActivity_clicking.cs">
<tr>
<td id="file-peoplelistactivity_clicking-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-peoplelistactivity_clicking-cs-LC1" class="blob-code blob-code-inner js-file-line">  private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-peoplelistactivity_clicking-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-peoplelistactivity_clicking-cs-LC3" class="blob-code blob-code-inner js-file-line">      var person = _peopleList[e.Position];</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-peoplelistactivity_clicking-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-peoplelistactivity_clicking-cs-LC5" class="blob-code blob-code-inner js-file-line">      var uri = Android.Net.Uri.Parse(&quot;tel:&quot; + person.PhoneNumber);</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-peoplelistactivity_clicking-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-peoplelistactivity_clicking-cs-LC7" class="blob-code blob-code-inner js-file-line">      var intent = new Intent(Intent.ActionDial, uri);</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-peoplelistactivity_clicking-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-peoplelistactivity_clicking-cs-LC9" class="blob-code blob-code-inner js-file-line">      StartActivity(intent);</td>
</tr>
<tr>
<td id="file-peoplelistactivity_clicking-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-peoplelistactivity_clicking-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/c5e4309e60888a66284df0dede98d877/raw/b0078b3ff7fe9656c97da6127f3e4e8310e552e7/PeopleListActivity_clicking.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c5e4309e60888a66284df0dede98d877#file-peoplelistactivity_clicking-cs" class="Link--inTextBlock"><br />
          PeopleListActivity_clicking.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>What those 4 lines of code do, is when tapping an entry from the list:</p>
<p><figure id="attachment_1589" aria-describedby="caption-attachment-1589" style="width: 240px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1589" data-permalink="https://www.codejourney.net/xamarin-android-intents/monayback_listofpeople/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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="MonayBack_ListOfPeople" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-1589 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?resize=240%2C400&#038;ssl=1" alt="MonayBack_ListOfPeople" width="240" height="400" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 240px) 100vw, 240px" /><figcaption id="caption-attachment-1589" class="wp-caption-text">MoneyBack &#8211; people list Activity</figcaption></figure></p>
<p>it opens the phone dialer app with selected person&#8217;s phone number to call:</p>
<p><figure id="attachment_1594" aria-describedby="caption-attachment-1594" style="width: 242px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1594" data-permalink="https://www.codejourney.net/xamarin-android-intents/moneyback_phonedialercall/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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_phoneDialerCall" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-1594 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?resize=242%2C403&#038;ssl=1" alt="MoneyBack_phoneDialerCall.png" width="242" height="403" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 242px) 100vw, 242px" /><figcaption id="caption-attachment-1594" class="wp-caption-text">Phone Dialer opened</figcaption></figure></p>
<p><span style="font-size: 10pt;">NOTE: If I had more than one dialer app installed (if the other dialer app has itself registered as receiver for <em>ACTION_DIAL, </em>of course) Android would ask me to choose which app I want to use.</p>
<p></span></p>
<p>How did that happen? First actually interesting line of code is the following one:</p>
<pre><pre class="brush: csharp; title: ; notranslate">var intent = new Intent(Intent.ActionDial, uri);</pre>
<p>It creates a new <em>Intent</em>, giving to it &#8211; as we said in the previous paragraph &#8211; two things:</p>
<ul>
<li><em>what</em> we want to do &#8211; it this case, we set <em>action </em>to <span style="color: #ff9900;">Intent.ActionDial</span>, which corresponds to <a href="https://developer.android.com/reference/android/content/Intent.html#ACTION_DIAL" target="_blank" rel="noopener">ACTION_DIAL</a> Activity Action</li>
<li>operation&#8217;s <em>parameters</em> &#8211; in our case there is just one parameter, which is the phone number in <a href="https://developer.xamarin.com/api/type/Android.Net.Uri/" target="_blank" rel="noopener">URI</a> format</li>
</ul>
<p>For each type of Activity Action you want to trigger, you can find what parameters it needs in <a href="https://developer.android.com/reference/android/content/Intent.html" target="_blank" rel="noopener">official Android Documentation</a>.</p>
<p>In the end, we just need to finally start a new Activity with the <em>Intent</em> we just created:</p>
<pre><pre class="brush: csharp; title: ; notranslate">StartActivity(intent);</pre>
<p>and we&#8217;re all done.</p>
<h2>Intent as a message</h2>
<p>Now, let&#8217;s think about our app as a set of Activities, which are <em>loosly-coopled</em>. We have <span style="color: #ff9900;">MainActivity</span> class, which represents the main screen of our app. We&#8217;ve also built another Activity, which we want to open from the main one. In that case, we already see everything which fits into intent-as-a-message template &#8211; two Activities want to &#8220;talk&#8221; with each other.</p>
<p>In <em>MoneyBack</em> I changed the <span style="color: #ff9900;">MainActivity</span> to look as follows:</p>
<p><figure id="attachment_1624" aria-describedby="caption-attachment-1624" style="width: 223px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1624" data-permalink="https://www.codejourney.net/xamarin-android-intents/moneyback_mainactivity/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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_MainActivity" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-1624 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?resize=223%2C371&#038;ssl=1" alt="MoneyBack_MainActivity.png" width="223" height="371" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 223px) 100vw, 223px" /><figcaption id="caption-attachment-1624" class="wp-caption-text">MoneyBack &#8211; <em>MainActivity</em></figcaption></figure></p>
<p>When clicking on &#8220;People Management&#8221; button, I&#8217;d like another Activity (represented by <span style="color: #ff9900;">PeopleActivity</span> class) to open.</p>
<p>In order to achieve that, <em>MoneyBack</em> executes the following code when clicking on the button:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46271232" 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_peoplemanagementclick-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_peopleManagementClick.cs content, created by dsibinski on 09:28AM on April 01, 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_peopleManagementClick.cs">
<tr>
<td id="file-mainactivity_peoplemanagementclick-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_peoplemanagementclick-cs-LC1" class="blob-code blob-code-inner js-file-line">  private void _btnPeople_Click(object sender, EventArgs e)</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_peoplemanagementclick-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_peoplemanagementclick-cs-LC3" class="blob-code blob-code-inner js-file-line">      var intent = new Intent(this, typeof(PeopleActivity));</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_peoplemanagementclick-cs-LC4" class="blob-code blob-code-inner js-file-line">      StartActivity(intent);</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_peoplemanagementclick-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/87ace30937c460184ccb36d59919727c/raw/ce3100662ce3e8a8746a713fed52ca9b7940fc46/MainActivity_peopleManagementClick.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/87ace30937c460184ccb36d59919727c#file-mainactivity_peoplemanagementclick-cs" class="Link--inTextBlock"><br />
          MainActivity_peopleManagementClick.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>What you can see here, is that we create a new <em>Intent</em> that takes two parameters:</p>
<ul>
<li><em>Context </em>&#8211; being the class storing information about current application&#8217;s/Activity&#8217;s state, from the place where the <em>Intent</em> is created; in our case, we set it to <span style="color: #ff9900;">this</span>, which is the calling Activity class reference. Context is our message&#8217;s <strong>sender</strong></li>
<li><em>Type</em> &#8211; this is our message&#8217;s <strong>recipient</strong>; in our case it&#8217;s the <span style="color: #ff9900;">Type</span> of destination Activity we want to start (<span style="color: #ff9900;">PeopleActivity</span>)</li>
</ul>
<p><span style="font-size: 10pt;">NOTE: Notice that we have no <em>content</em> provided in that case.</p>
<p></span></p>
<p>Then we just start the Activity as in the previous example and another screen appears:</p>
<p><figure id="attachment_1645" aria-describedby="caption-attachment-1645" style="width: 217px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1645" data-permalink="https://www.codejourney.net/xamarin-android-intents/moneyback_peopleactivity/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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_PeopleActivity" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-1645 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?resize=217%2C362&#038;ssl=1" alt="MoneyBack_PeopleActivity.png" width="217" height="362" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 217px) 100vw, 217px" /><figcaption id="caption-attachment-1645" class="wp-caption-text">MoneyBack &#8211; PeopleActivity</figcaption></figure></p>
<p>If the back button is now pressed, it goes back to previous (calling) Activity. That&#8217;s how the Activities stack is built, by the way <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>
<h4>Passing additional content using Intent as a message</h4>
<p>I mentioned we can also pass some additional data (message&#8217;s <strong>content</strong>) within an <em>Intent</em>. In the above example we didn&#8217;t do it, because there is no sense to pass anything from <span style="color: #ff9900;">MainActivity</span> to <span style="color: #ff9900;">PeopleActivity</span> for now. However, if we&#8217;d like to do that, we can add a simple modification to button&#8217;s pressing code in <span style="color: #ff9900;">MainActivity</span>:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46271394" 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_peoplemanagementclick_msg-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_peopleManagementClick_msg.cs content, created by dsibinski on 09:39AM on April 01, 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_peopleManagementClick_msg.cs">
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC1" class="blob-code blob-code-inner js-file-line">  private void _btnPeople_Click(object sender, EventArgs e)</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC3" class="blob-code blob-code-inner js-file-line">      var intent = new Intent(this, typeof(PeopleActivity));</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC5" class="blob-code blob-code-inner js-file-line">      var msgContent = &quot;Hello! This is a secret sent from MainActivity! Don&#39;t tell anyone!&quot;;</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC6" class="blob-code blob-code-inner js-file-line">      intent.PutExtra(&quot;secret_message&quot;, msgContent);</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC7" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-LC8" class="blob-code blob-code-inner js-file-line">      StartActivity(intent);</td>
</tr>
<tr>
<td id="file-mainactivity_peoplemanagementclick_msg-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_peoplemanagementclick_msg-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/c41976d7f7873ab870f1a41fc0b9540c/raw/e3cbbe0505a984c152a7646452e374cd15ccb451/MainActivity_peopleManagementClick_msg.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c41976d7f7873ab870f1a41fc0b9540c#file-mainactivity_peoplemanagementclick_msg-cs" class="Link--inTextBlock"><br />
          MainActivity_peopleManagementClick_msg.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 see, I used <span style="color: #ff9900;">PutExtra</span> method of the <span style="color: #ff9900;">Intent </span>class to insert <span style="color: #ff9900;"><em>msgContent</em></span> into Intent&#8217;s simple key-value Bundle Dictionary called <em>Extras, </em>using &#8220;secret_message&#8221; string as a key. Then, in the destination Activity&#8217;s <span style="color: #ff9900;">OnCreate</span> method we can retrieve such value back using <span style="color: #ff9900;">Intent.Extras.GetString</span> (for <span style="color: #ff9900;">String</span> data type) method:</p>
<p><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1670" data-permalink="https://www.codejourney.net/xamarin-android-intents/moneyback_intentextrasretrieve/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?fit=975%2C504&amp;ssl=1" data-orig-size="975,504" 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_IntentExtrasRetrieve" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?fit=975%2C504&amp;ssl=1" class=" wp-image-1670 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?resize=584%2C302&#038;ssl=1" alt="MoneyBack_IntentExtrasRetrieve.PNG" width="584" height="302" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?w=975&amp;ssl=1 975w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?resize=300%2C155&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?resize=768%2C397&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?resize=720%2C372&amp;ssl=1 720w" sizes="auto, (max-width: 584px) 100vw, 584px" /></p>
<p>This kind of data-passing between Activities using <span style="color: #ff9900;">Intent.Extras</span> should be used only for simple, mostly key-value data transferring. There are other methods for passing/storing more complex data in an app or between different applications.</p>
<h2>Summary</h2>
<p>Today we&#8217;ve seen what is an <em>Intent</em>, how to use it to trigger external actions such as calling a phone number, sending email etc., but also how to use it to handle navigation between Activities. We&#8217;ve also passed key-value data between two Activities using <span style="color: #ff9900;">Intent.Extras</span>.</p>
<p><em>Intent</em>, as well as <a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener">Activity</a>, is one of the fundamental concepts of Android. It&#8217;s essential to know how <em>Intents</em> work, how they relate to <em>Activities</em>, <em>Services</em> (which we&#8217;ll also cover one day) and <em>Application Blocks.  </em>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/xamarin-android-intents/">Xamarin &#8211; Android Intents</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/xamarin-android-intents/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1499</post-id>	</item>
		<item>
		<title>Unit Testing Xamarin application</title>
		<link>https://www.codejourney.net/unit-testing-xamarin-application/</link>
					<comments>https://www.codejourney.net/unit-testing-xamarin-application/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 25 Mar 2017 23:07:19 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=1166</guid>

					<description><![CDATA[<p>Today we&#8217;ll see how to add unit tests to Xamarin Android application, testing both platform-independent logic and Android-specific features. Issue with unit tests in Visual Studio 2017 When I started to create my data access methods in MoneyBack, I really wanted to start writing even some basic unit tests of that logic. My first trial was to&#8230;</p>
<p>The post <a href="https://www.codejourney.net/unit-testing-xamarin-application/">Unit Testing Xamarin application</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today we&#8217;ll see how to add unit tests to Xamarin Android application, testing both platform-independent logic and Android-specific features.<br />
<span id="more-1166"></span></p>
<h2>Issue with unit tests in Visual Studio 2017</h2>
<p>When I started to create my data access methods in <em>MoneyBack</em>, I really wanted to start writing even some basic unit tests of that logic.</p>
<p>My first trial was to add a new project to my solution which contains unit tests. So I checked what kind of projects templates I have available and I I found <strong>Unit Test App (Android) </strong>project template and added it to my solution. Generated project contained <span style="color: #ff6600;"><em>TestsSample</em> </span>class with some unit-looking tests methods, but I had no idea how to execute them. With ReSharper installed, I didn&#8217;t have any &#8220;Run Tests&#8221; option on this project. I read somewhere on the web that this project type is used to execute tests on the device, but I couldn&#8217;t figure out how to do it. I gave up.</p>
<p>Then I found another project template &#8211; <strong>Class Library (Android) with nUnit</strong>. Sounds better, <em>nUnit</em> in the name suggests unit tests, so I added this project to my solution. This time when right-clicking the project I had &#8220;Run Tests&#8221; option, but when clicking on it I got the following exception coming from ReSharper:</p>
<p><figure id="attachment_1200" aria-describedby="caption-attachment-1200" style="width: 1030px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1200" data-permalink="https://www.codejourney.net/unit-testing-xamarin-application/resharper_exc/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?fit=1030%2C829&amp;ssl=1" data-orig-size="1030,829" 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_Exc" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?fit=1024%2C824&amp;ssl=1" class="wp-image-1200 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?resize=1030%2C829&#038;ssl=1" alt="ReSharper_Exc" width="1030" height="829" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?w=1030&amp;ssl=1 1030w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?resize=300%2C241&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?resize=768%2C618&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?resize=1024%2C824&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?resize=720%2C579&amp;ssl=1 720w" sizes="auto, (max-width: 1030px) 100vw, 1030px" /><figcaption id="caption-attachment-1200" class="wp-caption-text">ReSharper error when executing unit tests</figcaption></figure></p>
<p>&#8220;Hmm&#8230; Visual Studio 2017&#8221;, I thought. &#8220;Some bugs for sure&#8221;. And I&#8230;</p>
<p>&#8230; didn&#8217;t give up this time and with some help of folks from StackOverflow I figured out how unit tests should be done in Xamarin app. Let&#8217;s see that in the next chapters.</p>
<h2>Levels of testing Xamarin application</h2>
<p>There are basically three &#8220;levels&#8221; of testing Xamarin apps:</p>
<ol>
<li><strong>Classic unit tests of pure .NET/Mono</strong>
<ul>
<li>standard, good old unit tests of logic independent from targeting platform (Xamarin.Android/iOS/Windows Phone)</li>
<li>unit-testing frameworks can be used (nUnit / xUnit)</li>
</ul>
</li>
<li><strong>Platform-specific tests</strong>
<ul>
<li>unit tests of functionalities specific to targeting platform (e.g. Bluetooth, Location, GPS, SMS etc.)</li>
<li>specific for each platform</li>
<li>don&#8217;t contain GUI tests</li>
<li>executed on the emulator/device</li>
</ul>
</li>
<li><strong>UI tests</strong>
<ul>
<li>tests of UI elements of the app and how those react for input (touch) events</li>
<li>executed by cloud/testing lab services (local or remote)</li>
</ul>
</li>
</ol>
<p>We&#8217;ll dive into the first two, UI tests is more complex topic, which requires setting up tests lab or using cloud testing services. For small projects, in the beginning it&#8217;s not necessary.</p>
<h2>Classic platform-independent unit tests</h2>
<p>In order to simply use ReSharper for executing unit tests of logic, which is independent from Android/iOS/Windows Phone, there is a need to add a new project using template <strong>Unit Test Project (.NET Framework) </strong>to our Xamarin solution.</p>
<p>To such project, you can add your favourite unit-testing framework (such as <em>nUnit</em> or <em>xUnit</em>) by simply installing it from Nuget.  After, ReSharper allows to run your unit tests as in old good times:</p>
<p><figure id="attachment_1246" aria-describedby="caption-attachment-1246" style="width: 714px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1246" data-permalink="https://www.codejourney.net/unit-testing-xamarin-application/tests_rsharper/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/tests_rsharper.png?fit=714%2C149&amp;ssl=1" data-orig-size="714,149" 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="tests_rsharper" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/tests_rsharper.png?fit=714%2C149&amp;ssl=1" class="wp-image-1246 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/tests_rsharper.png?resize=714%2C149&#038;ssl=1" alt="tests_rsharper.PNG" width="714" height="149" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/tests_rsharper.png?w=714&amp;ssl=1 714w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/tests_rsharper.png?resize=300%2C63&amp;ssl=1 300w" sizes="auto, (max-width: 714px) 100vw, 714px" /><figcaption id="caption-attachment-1246" class="wp-caption-text">nUnit tests executed by ReSharper</figcaption></figure></p>
<p>The exception I was getting with ReSharper previously was because I added the project using template <em>Class Library (Android) </em>which has its target set to Android device/emulator. ReSharper doesn&#8217;t know about any Android-specific (or Xamarin-specific) testing, so it was displaying unhandled error.</p>
<h2>Platform-specific unit tests</h2>
<p>In order to test platform-specific (in out case Android-specific) functionalities of your application, the tests need targeting runtime environment to run. It means they need to be executed on the physical device or emulator. Providers of the most popular unit-testing frameworks created wrappers for on-device testing. I&#8217;m using <a href="https://github.com/nunit/nunit.xamarin" target="_blank" rel="noopener">NUnit Xamarin Runners</a>.</p>
<p>First of all, a new project should be added to our solution. To make things easier, download <a href="https://marketplace.visualstudio.com/items?itemName=NUnitDevelopers.NUnitTemplatesforVisualStudio" target="_blank" rel="noopener">NUnit Templates for Visual Studio</a> (although it officially supports VS up to 2015, it also works in VS 2017) and install it. After, add new project using appropriate template &#8211; I chose <strong>NUnit 3 Test Project (Android)</strong>. What&#8217;s interesting, the newly created project contains <em><span style="color: #ff6600;">MainActivity</span> </em>class with the following content:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46061652" 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_tests-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_Tests.cs content, created by dsibinski on 10:13PM on March 25, 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_Tests.cs">
<tr>
<td id="file-mainactivity_tests-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_tests-cs-LC1" class="blob-code blob-code-inner js-file-line">  public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_tests-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_tests-cs-LC3" class="blob-code blob-code-inner js-file-line">      protected override void OnCreate(Bundle savedInstanceState)</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_tests-cs-LC4" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_tests-cs-LC5" class="blob-code blob-code-inner js-file-line">          base.OnCreate(savedInstanceState);</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_tests-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_tests-cs-LC7" class="blob-code blob-code-inner js-file-line">          global::Xamarin.Forms.Forms.Init(this, savedInstanceState);</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_tests-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_tests-cs-LC9" class="blob-code blob-code-inner js-file-line">          // This will load all tests within the current project</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_tests-cs-LC10" class="blob-code blob-code-inner js-file-line">          var nunit = new NUnit.Runner.App();</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-mainactivity_tests-cs-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-mainactivity_tests-cs-LC12" class="blob-code blob-code-inner js-file-line">          // If you want to add tests in another assembly</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-mainactivity_tests-cs-LC13" class="blob-code blob-code-inner js-file-line">          //nunit.AddTestAssembly(typeof(MyTests).Assembly);</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-mainactivity_tests-cs-LC14" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-mainactivity_tests-cs-LC15" class="blob-code blob-code-inner js-file-line">          // Do you want to automatically run tests when the app starts?</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-mainactivity_tests-cs-LC16" class="blob-code blob-code-inner js-file-line">          nunit.AutoRun = true;</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-mainactivity_tests-cs-LC17" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-mainactivity_tests-cs-LC18" class="blob-code blob-code-inner js-file-line">          LoadApplication(nunit);</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-mainactivity_tests-cs-LC19" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-mainactivity_tests-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-mainactivity_tests-cs-LC20" 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/ea386a734c1021a4ba5430e0306ab732/raw/fc5a31fd21ae36379882b0993be91d216944c4ec/MainActivity_Tests.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/ea386a734c1021a4ba5430e0306ab732#file-mainactivity_tests-cs" class="Link--inTextBlock"><br />
          MainActivity_Tests.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, this is an <a href="https://www.codejourney.net/2017/03/xamarin-android-activities/" target="_blank" rel="noopener">Activity</a>, so it will be launched as a separate app with its own GUI. It&#8217;s built using Xamarin.Forms. The comments in auto-generated class are obvious, so I won&#8217;t explain the details here. That&#8217;s just what nUnit wrapper for Android on-device tests does &#8211; it allows to be run as a separate, small application with a GUI allowing to run unit tests directly on the device (similarly to ReSharper tests runner we use directly in Visual Studio).</p>
<p>One testable piece of <em>MoneyBack</em> application is the <em>Repository</em> used for database operations (by the way I refactored and made it generic, you can see how it looks currently on <a href="https://github.com/dsibinski/MoneyBack" target="_blank" rel="noopener">GitHub</a>), so I added <span style="color: #ff6600;"><em>RepositoryTests</em></span> class to <em>MoneyBack.Android.Tests</em> project with two test methods:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46061804" 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-repositorytests_methods-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="RepositoryTests_methods.cs content, created by dsibinski on 10:22PM on March 25, 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="RepositoryTests_methods.cs">
<tr>
<td id="file-repositorytests_methods-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-repositorytests_methods-cs-LC1" class="blob-code blob-code-inner js-file-line">[Test]</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-repositorytests_methods-cs-LC2" class="blob-code blob-code-inner js-file-line">public void one_new_person_inserted_adds_one_new_row()</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-repositorytests_methods-cs-LC3" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-repositorytests_methods-cs-LC4" class="blob-code blob-code-inner js-file-line">    // given</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-repositorytests_methods-cs-LC5" class="blob-code blob-code-inner js-file-line">    var person = new Person()</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-repositorytests_methods-cs-LC6" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-repositorytests_methods-cs-LC7" class="blob-code blob-code-inner js-file-line">        Name = &quot;A&quot;,</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-repositorytests_methods-cs-LC8" class="blob-code blob-code-inner js-file-line">        LastName = &quot;B&quot;</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-repositorytests_methods-cs-LC9" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-repositorytests_methods-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-repositorytests_methods-cs-LC11" class="blob-code blob-code-inner js-file-line">    var repo = new Repository&lt;Person&gt;(InMemorySqliteConnection);</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-repositorytests_methods-cs-LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-repositorytests_methods-cs-LC13" class="blob-code blob-code-inner js-file-line">    // when</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-repositorytests_methods-cs-LC14" class="blob-code blob-code-inner js-file-line">    var numRows = repo.Insert(person).Result;</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-repositorytests_methods-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-repositorytests_methods-cs-LC16" class="blob-code blob-code-inner js-file-line">    // then</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-repositorytests_methods-cs-LC17" class="blob-code blob-code-inner js-file-line">    Assert.AreEqual(1, numRows);</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-repositorytests_methods-cs-LC18" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-repositorytests_methods-cs-LC19" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-repositorytests_methods-cs-LC20" class="blob-code blob-code-inner js-file-line">[Test]</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-repositorytests_methods-cs-LC21" class="blob-code blob-code-inner js-file-line">public void new_person_added_has_id_primarykey_generated()</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-repositorytests_methods-cs-LC22" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-repositorytests_methods-cs-LC23" class="blob-code blob-code-inner js-file-line">    // given</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-repositorytests_methods-cs-LC24" class="blob-code blob-code-inner js-file-line">    var person1 = new Person</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-repositorytests_methods-cs-LC25" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-repositorytests_methods-cs-LC26" class="blob-code blob-code-inner js-file-line">        Name = &quot;A&quot;,</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-repositorytests_methods-cs-LC27" class="blob-code blob-code-inner js-file-line">        LastName = &quot;B&quot;</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-repositorytests_methods-cs-LC28" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
<td id="file-repositorytests_methods-cs-LC29" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
<td id="file-repositorytests_methods-cs-LC30" class="blob-code blob-code-inner js-file-line">    var person2 = new Person</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
<td id="file-repositorytests_methods-cs-LC31" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
<td id="file-repositorytests_methods-cs-LC32" class="blob-code blob-code-inner js-file-line">        Name = &quot;A&quot;,</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
<td id="file-repositorytests_methods-cs-LC33" class="blob-code blob-code-inner js-file-line">        LastName = &quot;B&quot;</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
<td id="file-repositorytests_methods-cs-LC34" class="blob-code blob-code-inner js-file-line">    };</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
<td id="file-repositorytests_methods-cs-LC35" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
<td id="file-repositorytests_methods-cs-LC36" class="blob-code blob-code-inner js-file-line">    var repo = new Repository&lt;Person&gt;(InMemorySqliteConnection);</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
<td id="file-repositorytests_methods-cs-LC37" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L38" class="blob-num js-line-number js-blob-rnum" data-line-number="38"></td>
<td id="file-repositorytests_methods-cs-LC38" class="blob-code blob-code-inner js-file-line">    // when</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L39" class="blob-num js-line-number js-blob-rnum" data-line-number="39"></td>
<td id="file-repositorytests_methods-cs-LC39" class="blob-code blob-code-inner js-file-line">    var n1 = repo.Insert(person1).Result; // getting Result in order to force Task&#39;s completion before continuing</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L40" class="blob-num js-line-number js-blob-rnum" data-line-number="40"></td>
<td id="file-repositorytests_methods-cs-LC40" class="blob-code blob-code-inner js-file-line">    var n2 = repo.Insert(person2).Result;</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L41" class="blob-num js-line-number js-blob-rnum" data-line-number="41"></td>
<td id="file-repositorytests_methods-cs-LC41" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L42" class="blob-num js-line-number js-blob-rnum" data-line-number="42"></td>
<td id="file-repositorytests_methods-cs-LC42" class="blob-code blob-code-inner js-file-line">    // then</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L43" class="blob-num js-line-number js-blob-rnum" data-line-number="43"></td>
<td id="file-repositorytests_methods-cs-LC43" class="blob-code blob-code-inner js-file-line">    Assert.Greater(person1.Id, 0);</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L44" class="blob-num js-line-number js-blob-rnum" data-line-number="44"></td>
<td id="file-repositorytests_methods-cs-LC44" class="blob-code blob-code-inner js-file-line">    Assert.AreEqual(person2.Id, person1.Id + 1);</td>
</tr>
<tr>
<td id="file-repositorytests_methods-cs-L45" class="blob-num js-line-number js-blob-rnum" data-line-number="45"></td>
<td id="file-repositorytests_methods-cs-LC45" 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/2cefa097384d3c5e33595f37392cc330/raw/444e616d3480cdad0bda4c96e7112c7e65b2f698/RepositoryTests_methods.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/2cefa097384d3c5e33595f37392cc330#file-repositorytests_methods-cs" class="Link--inTextBlock"><br />
          RepositoryTests_methods.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>The interesting part is that as I&#8217;m using <a href="https://www.codejourney.net/2017/03/using-sqlite-database-in-xamarin-android/" target="_blank" rel="noopener">SQLite database in my app</a>, I wanted to test it without creating database file on the device. For that purpose, when creating <em><span style="color: #ff6600;">SQLiteAsyncConnection</span> </em>in order<em> </em>to initialize my <em><span style="color: #ff6600;">Repository</span>, </em>I passed to its constructor a <em>&#8220;:memory:&#8221;</em> string, which makes SQLite database created <a href="https://sqlite.org/inmemorydb.html" target="_blank" rel="noopener">in-memory</a> (there is no physical file created):</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist46061888" 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-repositorytests_sqlite-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="RepositoryTests_sqlite.cs content, created by dsibinski on 10:27PM on March 25, 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="RepositoryTests_sqlite.cs">
<tr>
<td id="file-repositorytests_sqlite-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-repositorytests_sqlite-cs-LC1" class="blob-code blob-code-inner js-file-line">  public SQLiteAsyncConnection InMemorySqliteConnection;</td>
</tr>
<tr>
<td id="file-repositorytests_sqlite-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-repositorytests_sqlite-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-repositorytests_sqlite-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-repositorytests_sqlite-cs-LC3" class="blob-code blob-code-inner js-file-line">  [OneTimeSetUp]</td>
</tr>
<tr>
<td id="file-repositorytests_sqlite-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-repositorytests_sqlite-cs-LC4" class="blob-code blob-code-inner js-file-line">  public void Init()</td>
</tr>
<tr>
<td id="file-repositorytests_sqlite-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-repositorytests_sqlite-cs-LC5" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-repositorytests_sqlite-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-repositorytests_sqlite-cs-LC6" class="blob-code blob-code-inner js-file-line">      InMemorySqliteConnection = new SQLiteAsyncConnection(&quot;:memory:&quot;);</td>
</tr>
<tr>
<td id="file-repositorytests_sqlite-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-repositorytests_sqlite-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/e205d0eacd107226c0986a2b9d2d8422/raw/53f9fb2a2be3c5f28320fbc09049b087694ed624/RepositoryTests_sqlite.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e205d0eacd107226c0986a2b9d2d8422#file-repositorytests_sqlite-cs" class="Link--inTextBlock"><br />
          RepositoryTests_sqlite.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>&nbsp;</p>
<p>Such database lives in device&#8217;s memory only for the time of our unit tests.</p>
<p>After having tests written, there&#8217;s a time to execute them. As the project contains <em><span style="color: #ff6600;">MainActivity</span> </em>class, we simply deploy and run it on a device/emulator, which presents the following view:</p>
<p><figure id="attachment_1306" aria-describedby="caption-attachment-1306" style="width: 210px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1306" data-permalink="https://www.codejourney.net/unit-testing-xamarin-application/screenshot_2017-03-25-23-31-44/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.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="Screenshot_2017-03-25-23-31-44" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?fit=576%2C1024&amp;ssl=1" class=" wp-image-1306 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?resize=210%2C374&#038;ssl=1" alt="Screenshot_2017-03-25-23-31-44.png" width="210" height="374" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?w=1080&amp;ssl=1 1080w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?resize=720%2C1280&amp;ssl=1 720w" sizes="auto, (max-width: 210px) 100vw, 210px" /><figcaption id="caption-attachment-1306" class="wp-caption-text">Device &#8211; tests results</figcaption></figure></p>
<p>If any of our tests is not passed, we can see the failure&#8217;s details:</p>
<p><figure id="attachment_1311" aria-describedby="caption-attachment-1311" style="width: 219px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1311" data-permalink="https://www.codejourney.net/unit-testing-xamarin-application/screenshot_2017-03-25-21-23-07/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.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="Screenshot_2017-03-25-21-23-07" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?fit=576%2C1024&amp;ssl=1" class=" wp-image-1311 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?resize=219%2C389&#038;ssl=1" alt="Screenshot_2017-03-25-21-23-07.png" width="219" height="389" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?w=1080&amp;ssl=1 1080w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?resize=720%2C1280&amp;ssl=1 720w" sizes="auto, (max-width: 219px) 100vw, 219px" /><figcaption id="caption-attachment-1311" class="wp-caption-text">Device &#8211; test failed</figcaption></figure></p>
<p>We can of course debug our units tests in Visual Studio. The GUI on the device also allows to re-run the tests and see results of all of them.</p>
<h2>Summary</h2>
<p>We&#8217;ve seen how to add two new projects to Xamarin solution: one containing platform-independent unit tests (old good ones), the other one testing Android-specific stuff which is run directly on the device or emulator.</p>
<p>For bigger and more &#8220;real&#8221; apps, UI testing would also be necessary. This however requires using some cloud testing lab or setting up your own testing environment. More details can be found <a href="https://developer.xamarin.com/guides/testcloud/introduction-to-test-cloud/" target="_blank" rel="noopener">here</a>.</p>
<p><span style="text-decoration: underline;"><strong>If you have any experience in testing Xamarin applications, share your insights/advices <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;" /></strong></span></p>
<h2> </h2>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/unit-testing-xamarin-application/">Unit Testing Xamarin application</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/unit-testing-xamarin-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1166</post-id>	</item>
		<item>
		<title>Using SQLite database in Xamarin.Android</title>
		<link>https://www.codejourney.net/using-sqlite-database-in-xamarin-android/</link>
					<comments>https://www.codejourney.net/using-sqlite-database-in-xamarin-android/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 19 Mar 2017 22:32:29 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=970</guid>

					<description><![CDATA[<p>I started to define development tasks to be done within MoneyBack project in the coming days (maybe I&#8217;ll even publish my Trello board soon 🙂 ) and it turned out that each functionality the app is going to offer needs persistent storage (e.g. to store people, payments, events etc.). The obvious choice is the local database in which&#8230;</p>
<p>The post <a href="https://www.codejourney.net/using-sqlite-database-in-xamarin-android/">Using SQLite database in Xamarin.Android</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I started to define development tasks to be done within <em>MoneyBack</em> project in the coming days (maybe I&#8217;ll even publish my Trello board 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;" /> ) and it turned out that each functionality the app is going to offer needs persistent storage (e.g. to store people, payments, events etc.). The obvious choice is the local database in which I could store my entities and application&#8217;s data.</p>
<p>In this post, I&#8217;d like to show you how quickly and easily SQLite database can be added and started to be used in Xamarin.Android project using <a href="https://www.nuget.org/packages/sqlite-net/" target="_blank" rel="noopener">SQLite.NET</a> and Visual Studio 2017.<br />
<span id="more-970"></span></p>
<h2>What is SQLite?</h2>
<p><a href="http://sqlite.org/" target="_blank" rel="noopener">SQLite</a> is an open-source database engine, which allows to store data in SQL structures. The whole database is stored in a single file, which makes it easily manageable on mobile devices. It&#8217;s lightweight, small and easily portable. It&#8217;s also prepared to work on multiple platforms.</p>
<p>There are some limitations in contrast to &#8220;classic&#8221; SQL database engines, including:</p>
<ul>
<li>OUTER join syntax is not fully supported</li>
<li>for altering tables, only &#8220;RENAME&#8221; and &#8220;ADDCOLUMN&#8221; operations are available</li>
<li>writing to views is impossible (views are read-only).</li>
</ul>
<p>SQLite database can be easily operated using SQLite.NET ORM library available to download and install via Nuget. Let&#8217;s see how to do it.</p>
<h2>Installing SQLite.NET package</h2>
<p>In order to install SQLite.NET package, simply open Android.Xamarin solution in Visual Studio, open Package Manager Console and type the following command:</p>
<pre><pre class="brush: csharp; title: ; notranslate">install-package Sqlite-Net</pre>
<p>After few seconds, two files are added to our project:</p>
<p><figure id="attachment_1007" aria-describedby="caption-attachment-1007" style="width: 185px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1007" data-permalink="https://www.codejourney.net/using-sqlite-database-in-xamarin-android/sqlitenetfiles/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/SQLiteNetFiles.png?fit=315%2C420&amp;ssl=1" data-orig-size="315,420" 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="SQLiteNetFiles" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/SQLiteNetFiles.png?fit=315%2C420&amp;ssl=1" class=" wp-image-1007 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/SQLiteNetFiles.png?resize=185%2C247&#038;ssl=1" alt="SQLiteNetFiles" width="185" height="247" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/SQLiteNetFiles.png?w=315&amp;ssl=1 315w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/SQLiteNetFiles.png?resize=225%2C300&amp;ssl=1 225w" sizes="auto, (max-width: 185px) 100vw, 185px" /><figcaption id="caption-attachment-1007" class="wp-caption-text">Files added by SQLite.NET</figcaption></figure></p>
<p>It means we&#8217;re all set <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>Entity definition</h2>
<p>We have SQLite ORM ready to use. Now we need to define our first entity. In case of <em>MoneyBack</em>, I decided to start with defining <em>Person </em>(plural: <em>People</em>) entity. First thing we need to do is to define entity class. I created &#8220;Entities&#8221; folder for that and added the following class file:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45864679" 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-person-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="Person.cs content, created by dsibinski on 09:06PM on March 19, 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="Person.cs">
<tr>
<td id="file-person-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-person-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace MoneyBack.Entities</td>
</tr>
<tr>
<td id="file-person-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-person-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-person-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-person-cs-LC3" class="blob-code blob-code-inner js-file-line">    [Table(&quot;People&quot;)]</td>
</tr>
<tr>
<td id="file-person-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-person-cs-LC4" class="blob-code blob-code-inner js-file-line">    public class Person</td>
</tr>
<tr>
<td id="file-person-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-person-cs-LC5" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-person-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-person-cs-LC6" class="blob-code blob-code-inner js-file-line">        [PrimaryKey, AutoIncrement]</td>
</tr>
<tr>
<td id="file-person-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-person-cs-LC7" class="blob-code blob-code-inner js-file-line">        public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-person-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-person-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-person-cs-LC9" class="blob-code blob-code-inner js-file-line">        public string Name { get; set; }</td>
</tr>
<tr>
<td id="file-person-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-person-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-person-cs-LC11" class="blob-code blob-code-inner js-file-line">        public string LastName { get; set; }</td>
</tr>
<tr>
<td id="file-person-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-person-cs-LC12" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-person-cs-LC13" class="blob-code blob-code-inner js-file-line">        public string PhoneNumber { get; set; }</td>
</tr>
<tr>
<td id="file-person-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-person-cs-LC14" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-person-cs-LC15" class="blob-code blob-code-inner js-file-line">        public string Email { get; set; }</td>
</tr>
<tr>
<td id="file-person-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-person-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-person-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-person-cs-LC17" class="blob-code blob-code-inner js-file-line">        public override string ToString()</td>
</tr>
<tr>
<td id="file-person-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-person-cs-LC18" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-person-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-person-cs-LC19" class="blob-code blob-code-inner js-file-line">            return $&quot;[Person: Id={Id}, Name={Name}, LastName={LastName}, PhoneNumber={PhoneNumber}, Email={Email}]&quot;;</td>
</tr>
<tr>
<td id="file-person-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-person-cs-LC20" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-person-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-person-cs-LC21" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-person-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-person-cs-LC22" 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/a1d1ca6c5380e0acc5c439f3060da9cc/raw/afc1d9b4c0442489fdb760ba88e681d3663b9e07/Person.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/a1d1ca6c5380e0acc5c439f3060da9cc#file-person-cs" class="Link--inTextBlock"><br />
          Person.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Just a class, in which we define basic properties of a Person &#8211;<em> Name, LastName, PhoneNumber</em> and <em>Email</em>. As we are designing a database entities, we also need to have keys for each of them &#8211; in this case we add <em>Id</em> property, and decorate it with two attributes:</p>
<ul>
<li><em>PrimaryKeyAttribute</em> &#8211; marks the column as PRIMARY KEY</li>
<li><em>AutoIncrementAttribute</em> &#8211; marks the column with AUTO_INCREMENT (unique number is generated when a new record is added into a table).</li>
</ul>
<p>We also have <em>TableAttribute</em> defined on <em>Person</em> class. This attribute&#8217;s constructor takes a single argument <em>name</em>, which is the name of the table which will be created underneath. In our case, single entity is called <em>Person</em>, but the table should be named in plural (table == set of entities) so we want it to be called <em>People</em>.</p>
<p>I also implemented <em>ToString() </em>method in order to be able to easily see details of our entity if needed.</p>
<h2>Location of database file</h2>
<p>Before database can be used, a database file must be created on the device. ORM does it for us before any query is made on the database, but we need to specify where we want to keep the db file. On Android, it can be stored either on internal or external storage.</p>
<p>I created <em>Constants.cs</em> class in which I put a read-only constant string returning path to database file. As a folder to store db file, I used <em>Environment.GetFolderPath(Environment.SpecialFolder.Personal) </em>which returns local path defined in Android system&#8217;s environmental variable $HOME:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45865151" 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-constants_dbpath-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="Constants_dbPath.cs content, created by dsibinski on 09:30PM on March 19, 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="Constants_dbPath.cs">
<tr>
<td id="file-constants_dbpath-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-constants_dbpath-cs-LC1" class="blob-code blob-code-inner js-file-line">public class Constants</td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-constants_dbpath-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-constants_dbpath-cs-LC3" class="blob-code blob-code-inner js-file-line">    public static readonly string DbFilePath = </td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-constants_dbpath-cs-LC4" class="blob-code blob-code-inner js-file-line">        Path.Combine(</td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-constants_dbpath-cs-LC5" class="blob-code blob-code-inner js-file-line">                Environment.GetFolderPath(Environment.SpecialFolder.Personal), </td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-constants_dbpath-cs-LC6" class="blob-code blob-code-inner js-file-line">                &quot;moneyback.db&quot;</td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-constants_dbpath-cs-LC7" class="blob-code blob-code-inner js-file-line">        );</td>
</tr>
<tr>
<td id="file-constants_dbpath-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-constants_dbpath-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/d5fb45ea47ee86b0540bf9f68666d103/raw/f01a0588740a5477cc78d7ce8e9e89b80d95d299/Constants_dbPath.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/d5fb45ea47ee86b0540bf9f68666d103#file-constants_dbpath-cs" class="Link--inTextBlock"><br />
          Constants_dbPath.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<h2>Database access methods</h2>
<p>As soon as we have entity class defined and location of database file, we can start performing operations on the db &#8211; define tables, add new entities (rows), retrieve rows from the database, delete them etc. In general, it comes down to creating <em>SQLiteConnection </em>object and performing operations on it.</p>
<p>There are several approaches of exposing Data Access Layer services/methods &#8211; we can create a database service, entities repository or use complex services location and dependency injection in order to operate our persistent data. I don&#8217;t know what is a standard way in Android applications, but I decided to create a very simple repository for our <em>Person</em> entity and expose database-access methods in it:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45865287" 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-peoplerepository-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="PeopleRepository.cs content, created by dsibinski on 09:39PM on March 19, 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="PeopleRepository.cs">
<tr>
<td id="file-peoplerepository-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-peoplerepository-cs-LC1" class="blob-code blob-code-inner js-file-line">public class PeopleRepository</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-peoplerepository-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-peoplerepository-cs-LC3" class="blob-code blob-code-inner js-file-line">    private SQLiteConnection db = null;</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-peoplerepository-cs-LC4" class="blob-code blob-code-inner js-file-line">    protected static PeopleRepository me;</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-peoplerepository-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-peoplerepository-cs-LC6" class="blob-code blob-code-inner js-file-line">    static PeopleRepository()</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-peoplerepository-cs-LC7" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-peoplerepository-cs-LC8" class="blob-code blob-code-inner js-file-line">        me = new PeopleRepository();</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-peoplerepository-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-peoplerepository-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-peoplerepository-cs-LC11" class="blob-code blob-code-inner js-file-line">    protected PeopleRepository()</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-peoplerepository-cs-LC12" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-peoplerepository-cs-LC13" class="blob-code blob-code-inner js-file-line">        db = new SQLiteConnection(Constants.DbFilePath);</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-peoplerepository-cs-LC14" class="blob-code blob-code-inner js-file-line">        db.CreateTable&lt;Person&gt;();</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-peoplerepository-cs-LC15" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-peoplerepository-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-peoplerepository-cs-LC17" class="blob-code blob-code-inner js-file-line">    public static int SavePerson(Person person)</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-peoplerepository-cs-LC18" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-peoplerepository-cs-LC19" class="blob-code blob-code-inner js-file-line">        me.db.Insert(person);</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-peoplerepository-cs-LC20" class="blob-code blob-code-inner js-file-line">        return person.Id;</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-peoplerepository-cs-LC21" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-peoplerepository-cs-LC22" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-peoplerepository-cs-LC23" class="blob-code blob-code-inner js-file-line">    public static Person GetPerson(int id)</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-peoplerepository-cs-LC24" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-peoplerepository-cs-LC25" class="blob-code blob-code-inner js-file-line">        return me.db.Get&lt;Person&gt;(p =&gt; p.Id == id);</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-peoplerepository-cs-LC26" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-peoplerepository-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-peoplerepository-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/c8256dbaaf5970a512062aa3a9fe5ad3/raw/5371465e526cbf189e77c720e9f97e2b37748042/PeopleRepository.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c8256dbaaf5970a512062aa3a9fe5ad3#file-peoplerepository-cs" class="Link--inTextBlock"><br />
          PeopleRepository.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>I haven&#8217;t even created any abstract layer for the repository (e.g. interface), as I simply don&#8217;t know what approach I will use for the next entities. I&#8217;m not sure if the repository is the right choice. On the other hand, I don&#8217;t think such rather simple app requires something more. <span style="text-decoration: underline;"><strong>What do you think ?</p>
<p></strong></span></p>
<p>As you can see, <em>PeopleRepository</em> executes its static constructor when any of static methods is called for the first time, in which it instantiates <em>db</em> variable of type <em>SQLiteConnection</em>, giving it the path to db file we defined. If database file doesn&#8217;t exist, it will be automatically created. Then, <em>db.CreateTable&lt;Person&gt;()</em> creates <em>People</em> table if it doesn&#8217;t exist, according to what we defined in <em>Person</em> entity model.</p>
<p>Two static methods &#8211; <em>SavePerson</em> and <em>GetPerson </em>allow to save and retrieve <em>Person</em> entity to/from the database accordingly. The first one is additionally returning the integer <em>Id</em> of newly added row.</p>
<h2>Usage in the code</h2>
<p>I added two text fields to <em>MoneyBack</em> app to enter name and last name of person to be added and one button which actually allows to perform saving operation:</p>
<p><figure id="attachment_1088" aria-describedby="caption-attachment-1088" style="width: 233px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1088" data-permalink="https://www.codejourney.net/using-sqlite-database-in-xamarin-android/moneyback_savingperson/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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_SavingPerson" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-1088 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?resize=233%2C388&#038;ssl=1" alt="MoneyBack_SavingPerson.png" width="233" height="388" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 233px) 100vw, 233px" /><figcaption id="caption-attachment-1088" class="wp-caption-text">Adding new Person</figcaption></figure></p>
<p>On clicking the button, the following method is executed:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45865616" 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-addpersonbuttonclick-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="addPersonButtonClick.cs content, created by dsibinski on 09:58PM on March 19, 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="addPersonButtonClick.cs">
<tr>
<td id="file-addpersonbuttonclick-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-addpersonbuttonclick-cs-LC1" class="blob-code blob-code-inner js-file-line">private void _btnAddPerson_Click(object sender, EventArgs e)</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-addpersonbuttonclick-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-addpersonbuttonclick-cs-LC3" class="blob-code blob-code-inner js-file-line">    var name = _inputName.Text;</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-addpersonbuttonclick-cs-LC4" class="blob-code blob-code-inner js-file-line">    var lastName = _inputLastName.Text;</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-addpersonbuttonclick-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-addpersonbuttonclick-cs-LC6" class="blob-code blob-code-inner js-file-line">    var id = PeopleRepository.SavePerson(new Person</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-addpersonbuttonclick-cs-LC7" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-addpersonbuttonclick-cs-LC8" class="blob-code blob-code-inner js-file-line">        Name = name,</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-addpersonbuttonclick-cs-LC9" class="blob-code blob-code-inner js-file-line">        LastName = lastName</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-addpersonbuttonclick-cs-LC10" class="blob-code blob-code-inner js-file-line">    });</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-addpersonbuttonclick-cs-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-addpersonbuttonclick-cs-LC12" class="blob-code blob-code-inner js-file-line">    var person = PeopleRepository.GetPerson(id);</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-addpersonbuttonclick-cs-LC13" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-addpersonbuttonclick-cs-LC14" class="blob-code blob-code-inner js-file-line">    if (person == null)</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-addpersonbuttonclick-cs-LC15" class="blob-code blob-code-inner js-file-line">        Toast.MakeText(this, $&quot;Person: Name={name}, LastName={lastName} wasn&#39;t properly saved!&quot;, ToastLength.Long).Show();</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-addpersonbuttonclick-cs-LC16" class="blob-code blob-code-inner js-file-line">    else</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-addpersonbuttonclick-cs-LC17" class="blob-code blob-code-inner js-file-line">        Toast.MakeText(this, $&quot;Person saved, details: {person}&quot;, ToastLength.Long).Show();</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-addpersonbuttonclick-cs-LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-addpersonbuttonclick-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-addpersonbuttonclick-cs-LC19" 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/4b9472f0a5f787a265fee0982dfcec96/raw/5b9be5b6240b78b71654a2a3651315b9e508b3c6/addPersonButtonClick.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/4b9472f0a5f787a265fee0982dfcec96#file-addpersonbuttonclick-cs" class="Link--inTextBlock"><br />
          addPersonButtonClick.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>&nbsp;</p>
<p>Here&#8217;s the result of clicking the button in the app:</p>
<p><figure id="attachment_1093" aria-describedby="caption-attachment-1093" style="width: 249px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1093" data-permalink="https://www.codejourney.net/using-sqlite-database-in-xamarin-android/moneyback_savingperson_success/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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_SavingPerson_Success" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-1093 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?resize=249%2C415&#038;ssl=1" alt="MoneyBack_SavingPerson_Success.png" width="249" height="415" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 249px) 100vw, 249px" /><figcaption id="caption-attachment-1093" class="wp-caption-text">Person saved successfully</figcaption></figure></p>
<p>As you can see, in the toast message received, <em>Id</em> of the <em>Person</em> added has value 3. That&#8217;s because when I launched the app previously I&#8217;ve already added two new people. It shows that the data is really persistently stored and doesn&#8217;t disappear when the app is restarted.</p>
<h2>Summary</h2>
<p>Today we&#8217;ve seen that using SQLite file database in Xamarin.Android is very easy. Thanks to SQLite.NET lightweight ORM library we were able to quickly start working with the db.</p>
<p>To make the code ready for &#8220;production&#8221; use, I should also make it thread-safe (more details e.g. <a href="https://developer.xamarin.com/guides/android/application_fundamentals/data/part_2_configuration/" target="_blank" rel="noopener">here</a>) and add unit tests (which I&#8217;m BTW not able to do for now, I&#8217;m getting <em>TargetInvocationException</em> when trying to run any NUnit tests adding <em>Unit Test App (Android)</em> project in VS 2017&#8230;).</p>
<p>I&#8217;m also not sure if repository is a proper concept for managing local db entities in Android project. <span style="text-decoration: underline;"><strong>If you have more experience, I&#8217;d be grateful to hear how it should be done in a really &#8220;Android way&#8221; <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;" /></strong></span></p>
<p>The post <a href="https://www.codejourney.net/using-sqlite-database-in-xamarin-android/">Using SQLite database 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/using-sqlite-database-in-xamarin-android/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">970</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>Xamarin – Android Activities</title>
		<link>https://www.codejourney.net/xamarin-android-activities/</link>
					<comments>https://www.codejourney.net/xamarin-android-activities/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 11 Mar 2017 18:53:10 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=405</guid>

					<description><![CDATA[<p>Today we’re going to take a look at Android’s most basic and in the same time most important concept, which is an Activity. To create even the simplest “HelloWorld” app one should know what are the Activities and how to work with them. What is an Activity ? The simplest, an Activity is a single&#8230;</p>
<p>The post <a href="https://www.codejourney.net/xamarin-android-activities/">Xamarin – Android Activities</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p style="text-align: left;">Today we’re going to take a look at Android’s most basic and in the same time most important concept, which is an <strong>Activity</strong>. To create even the simplest “HelloWorld” app one should know what are the Activities and how to work with them.<br />
<span id="more-405"></span></p>
<h2>What is an Activity ?</h2>
<p style="text-align: left;" align="left">The simplest, an <strong>Activity is a single screen in Android application</strong>. The concept of Activities is unusual in programming and it&#8217;s specific to Android platform.</p>
<p style="text-align: left;" align="left">Every Activity in Xamarin consists of two components:</p>
<ul>
<li style="text-align: left;"><strong>UI </strong>(XML) &#8211; layout with user controls defined</li>
<li style="text-align: left;"><strong>Code </strong>(C#) &#8211; implementing the behavior</li>
</ul>
<p>Let&#8217;s consider email client application &#8211; it&#8217;d probably have several Activities: &#8220;New email&#8221;, &#8220;List of emails&#8221;, &#8220;Email details&#8221;, &#8220;Settings&#8221; &#8211; notice all of them having both UI and behavior. We&#8217;d probably need &#8220;Email sending service&#8221;, which doesn&#8217;t necessarily need UI, so it wouldn&#8217;t be created as an Activity, but rather as a separate class realizing concrete task.</p>
<p>As we can already see, every Android app contains several Activities:</p>
<p><figure id="attachment_484" aria-describedby="caption-attachment-484" style="width: 1823px" class="wp-caption alignnone"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="484" data-permalink="https://www.codejourney.net/xamarin-android-activities/activities/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?fit=1823%2C914&amp;ssl=1" data-orig-size="1823,914" 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="activities" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?fit=1024%2C513&amp;ssl=1" class="alignnone size-full wp-image-484" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?resize=1140%2C572&#038;ssl=1" alt="activities" width="1140" height="572" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?w=1823&amp;ssl=1 1823w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?resize=300%2C150&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?resize=768%2C385&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?resize=1024%2C513&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?resize=720%2C361&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /><figcaption id="caption-attachment-484" class="wp-caption-text">Android app composed of Activities, source: <a href="https://elearning.xamarin.com/android/AND101/2-activities/default" target="_blank" rel="noopener">elearning.xamarin.com</a></figcaption></figure></p>
<p>In most programming platforms, the application has a static method which is called on the application&#8217;s startup. This is not the case in Android &#8211; do you remember our <em>MainActivity </em>class <a href="https://www.codejourney.net/2017/03/hello-xamarin-world-first-steps/" target="_blank" rel="noopener">from the previous post</a> ? It&#8217;s decorated with <em>ActivityAttribute</em> which registers the Activity within the Android system, but what&#8217;s more important by having <em>MainLauncher</em> attribute&#8217;s property set to <strong>true</strong> it tells the system it&#8217;s the startup Activity for the application within which it&#8217;s registered. It means nothing more than when our app is launched, Android creates <em>MainActivity</em> as the first one from all Activities in our application. Apart from that, OS operates the <em>MainActivity</em> as all other Activities.</p>
<h2>Activities Back Stack</h2>
<p>Android app starts its own Activities from other Activities. It may also start Activities that are defined by different apps, e.g. your Android app can offer a possibility to send an email. You don&#8217;t have to implement your own email sending client for that &#8211; it&#8217;s possible to use already existing email sending Activities (using <a href="https://developer.xamarin.com/recipes/android/fundamentals/intent/" target="_blank" rel="noopener">Android Intents</a>, which we&#8217;ll also cover one day) registered within another apps installed in the system which expose such &#8220;external calling&#8221; possibility. Then, this external app launches looking as if it was the part of your application. This is very <strong>powerful!</strong></p>
<p>When your email is finally sent, you are redirected back to your app from which you triggered email&#8217;s sending. <em><strong>How is that possible?</p>
<p></strong></em></p>
<p>In order to ensure such way of functioning, Android keeps all the Activities needed to perform a certain job (even if they come from different apps) in the same <em>task</em>. The &#8220;scope&#8221; of a <em>task</em> (when new <em>task</em> is created, what Activities it contains etc.) depends, among others, on Android version (e.g. starting from Android 7.0 many apps can be started in multiple windows in the same time on a single screen &#8211; in that case, the system keeps a separate <em>task</em> for each window).</p>
<p>Within a particular <em>task</em>, several Activities are started. Each started Activity is pushed to the <strong>Activities</strong> <strong>Back Stack</strong>. The Activity being on the top of the stack <strong>has focus </strong>(is visible to the user). The previous Activities remain on the stack, but are stopped or even destroyed by Android system in certain cases (few more words about it in the next chapter).</p>
<p>Activities Back Stack is a LIFO objects structure: when user presses <a href="https://www.codejourney.net/wp-content/uploads/2017/03/android_back_button.png" target="_blank" rel="noopener"><strong>Back</strong> button</a> the current Activity is popped from the top of the stack and the state of the previous Activity is restored. The following figure visualizes this behavior:</p>
<p><figure id="attachment_550" aria-describedby="caption-attachment-550" style="width: 617px" class="wp-caption alignnone"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="550" data-permalink="https://www.codejourney.net/xamarin-android-activities/diagram_backstack/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/diagram_backstack.png?fit=617%2C195&amp;ssl=1" data-orig-size="617,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="diagram_backstack" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/diagram_backstack.png?fit=617%2C195&amp;ssl=1" class="alignnone size-full wp-image-550" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/diagram_backstack.png?resize=617%2C195&#038;ssl=1" alt="diagram_backstack" width="617" height="195" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/diagram_backstack.png?w=617&amp;ssl=1 617w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/diagram_backstack.png?resize=300%2C95&amp;ssl=1 300w" sizes="auto, (max-width: 617px) 100vw, 617px" /><figcaption id="caption-attachment-550" class="wp-caption-text">Activities Back Stack (LIFO) visualization, source: <a href="https://developer.android.com/guide/components/activities/tasks-and-back-stack.html" target="_blank" rel="noopener">developer.android.com</a></figcaption></figure></p>
<h2>Android Activities Lifecycle</h2>
<p>We already know the Activities are kept on Back Stack. We also need to know that Android OS may try to <strong>restart</strong> the application (after it crashed, for instance) at the last opened Activity. The OS may also <strong>pause</strong> the Activities when they&#8217;re not active or <strong>kill </strong>them when the device is low on memory. All those possible operations and states&#8217; changes form <strong>Android Activities Lifecycle</strong>, which is a set of defined states in which every Activity may be:</p>
<p><figure id="attachment_578" aria-describedby="caption-attachment-578" style="width: 1720px" class="wp-caption alignnone"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="578" data-permalink="https://www.codejourney.net/xamarin-android-activities/activities_states/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?fit=1720%2C347&amp;ssl=1" data-orig-size="1720,347" 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="activities_states" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?fit=1024%2C207&amp;ssl=1" class="alignnone size-full wp-image-578" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?resize=1140%2C230&#038;ssl=1" alt="activities_states" width="1140" height="230" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?w=1720&amp;ssl=1 1720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?resize=300%2C61&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?resize=768%2C155&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?resize=1024%2C207&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?resize=720%2C145&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /><figcaption id="caption-attachment-578" class="wp-caption-text">Activity states, source: <a href="https://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/" target="_blank" rel="noopener">developer.xamarin.com</a></figcaption></figure></p>
<p>Let&#8217;s see what those states mean:</p>
<ul>
<li><strong>Running</strong> &#8211; Activity is in the foreground (top of the activities stack); <span style="text-decoration: underline;">highest-priority Activity</span> for OS</li>
<li><strong>Paused </strong>&#8211; Activity is in this state when still visible, but covered by another non-full sized Activity or when the device enters sleep mode; <span style="text-decoration: underline;">second-highest-priority Activity</span> for OS</li>
<li><strong>Backgrounded/Stopped</strong>&#8211; Activity enters Backgrounded state when it&#8217;s overtaken by another, completely new Activity which is pushed on the top of the back stack; <span style="text-decoration: underline;">lowest-priority Activity</span> for OS, which will be killed firstly in order to free resources</li>
<li><strong>Restarted </strong>&#8211; this state is not visible on the diagram, however it&#8217;s possible that Android (e.g. user using task manager or similar app) kills the app being in any of above-mentioned states; if the user wants to go back to this Activity later, it must be restarted (previous state must be retrieved).</li>
</ul>
<h2>Handling states changes &#8211; lifecycle methods</h2>
<p>Android (and Xamarin) provides SDK methods that are called by the OS each time an Activity&#8217;s state changes. Those methods may be overridden and implemented for each Activity in order to react on states changes and ensure application&#8217;s stability. The following diagram visualizes the dependencies and flow of methods being called:</p>
<p><figure id="attachment_605" aria-describedby="caption-attachment-605" style="width: 399px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="605" data-permalink="https://www.codejourney.net/xamarin-android-activities/android_lifecycle_methods/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?fit=1720%2C1998&amp;ssl=1" data-orig-size="1720,1998" 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="android_lifecycle_methods" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?fit=882%2C1024&amp;ssl=1" class=" wp-image-605 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?resize=399%2C464&#038;ssl=1" alt="android_lifecycle_methods" width="399" height="464" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?w=1720&amp;ssl=1 1720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?resize=258%2C300&amp;ssl=1 258w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?resize=768%2C892&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?resize=882%2C1024&amp;ssl=1 882w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?resize=720%2C836&amp;ssl=1 720w" sizes="auto, (max-width: 399px) 100vw, 399px" /><figcaption id="caption-attachment-605" class="wp-caption-text">Android lifecycle methods, source: <a href="https://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/" target="_blank" rel="noopener">developer.xamarin.com</a></figcaption></figure></p>
<p>Let&#8217;s see in what cases the particular methods should be implemented:</p>
<ul>
<li><strong>OnCreate()</strong> &#8211; called when an Activity is created; used for initializing views and variables</li>
<li><strong>OnStart()</strong> &#8211; called immediately after <em>OnCreate()</em> finishes; UI refreshing can be handled here</li>
<li><strong>OnResume()</strong> &#8211; called after <em>OnStart()</em> finishes and also when Activity is restarted after being paused</li>
<li><strong>OnPause()</strong> &#8211; called when OS is about to pause or move the Activity to the background; here all resources-consuming objects should be cleaned-up, unsaved changes should be stored in some kind of persistent storage to be able to restore it when the Activity is revealed</li>
<li><strong>OnStop()</strong> &#8211; called when the Activity stops being visible to the user or is destroyed (e.g. when OS needs to release some resources)</li>
<li><strong>OnDestroy()</strong> &#8211; final method called on Activity just before it&#8217;s destroyed; it may not be called in some cases, so it&#8217;s better to clean-up resources in <em>OnPause()</em> and <em>OnStop()</em> methods.</li>
</ul>
<h2>Let&#8217;s see some code</h2>
<p>In order to really test those lifecycle methods, I added a stunning functionality to <em>MoneyBack</em> app:</p>
<p><figure id="attachment_629" aria-describedby="caption-attachment-629" style="width: 238px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="629" data-permalink="https://www.codejourney.net/xamarin-android-activities/screenshot_lifecycle/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?fit=768%2C1280&amp;ssl=1" data-orig-size="768,1280" 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="Screenshot_Lifecycle" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?fit=614%2C1024&amp;ssl=1" class=" wp-image-629 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?resize=238%2C397&#038;ssl=1" alt="Screenshot_Lifecycle" width="238" height="397" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?resize=180%2C300&amp;ssl=1 180w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?resize=614%2C1024&amp;ssl=1 614w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?resize=720%2C1200&amp;ssl=1 720w" sizes="auto, (max-width: 238px) 100vw, 238px" /><figcaption id="caption-attachment-629" class="wp-caption-text">Simple division Activity</figcaption></figure></p>
<p>As you could already realize, you can enter amount of money spent, number of people involved and it will make a simple division operation to split the costs equally. That&#8217;s already kinda costs splitting, 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>
<p>I implemented the lifecycle-control methods to check how it really behaves.</p>
<h3>OnCreate</h3>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45611437" 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_oncreate-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_OnCreate.cs content, created by dsibinski on 05:54PM on March 11, 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_OnCreate.cs">
<tr>
<td id="file-mainactivity_oncreate-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_oncreate-cs-LC1" class="blob-code blob-code-inner js-file-line">protected override void OnCreate(Bundle bundle)</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_oncreate-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_oncreate-cs-LC3" class="blob-code blob-code-inner js-file-line">    base.OnCreate(bundle);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_oncreate-cs-LC4" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_oncreate-cs-LC5" class="blob-code blob-code-inner js-file-line">    // Set our view from the &quot;main&quot; layout resource</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_oncreate-cs-LC6" class="blob-code blob-code-inner js-file-line">    SetContentView(Resource.Layout.Main);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_oncreate-cs-LC7" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_oncreate-cs-LC8" class="blob-code blob-code-inner js-file-line">    _amount = 0.00m;</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_oncreate-cs-LC9" class="blob-code blob-code-inner js-file-line">    _result = 0.00m;</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_oncreate-cs-LC10" class="blob-code blob-code-inner js-file-line">    _numberOfPeople = 0;</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-mainactivity_oncreate-cs-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-mainactivity_oncreate-cs-LC12" class="blob-code blob-code-inner js-file-line">    InitializeUserControls();</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-mainactivity_oncreate-cs-LC13" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-mainactivity_oncreate-cs-LC14" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-mainactivity_oncreate-cs-LC15" class="blob-code blob-code-inner js-file-line">// &#8230;</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-mainactivity_oncreate-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-mainactivity_oncreate-cs-LC17" class="blob-code blob-code-inner js-file-line">private void InitializeUserControls()</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-mainactivity_oncreate-cs-LC18" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-mainactivity_oncreate-cs-LC19" class="blob-code blob-code-inner js-file-line">    _inputAmount = this.FindViewById&lt;EditText&gt;(Resource.Id.inputAmount);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-mainactivity_oncreate-cs-LC20" class="blob-code blob-code-inner js-file-line">    _inputNumberOfPeople = this.FindViewById&lt;EditText&gt;(Resource.Id.inputNumberOfPeople);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-mainactivity_oncreate-cs-LC21" class="blob-code blob-code-inner js-file-line">    _txtResultDecimal = this.FindViewById&lt;EditText&gt;(Resource.Id.txtResultDecimal);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-mainactivity_oncreate-cs-LC22" class="blob-code blob-code-inner js-file-line">    _btnCalculate = this.FindViewById&lt;Button&gt;(Resource.Id.btnCalculate);</td>
</tr>
<tr>
<td id="file-mainactivity_oncreate-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-mainactivity_oncreate-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/5ace702ca7109b4f6ae08c35cce9ee84/raw/1fcf175d5220a6938bce340691a4a14e4f1ff391/MainActivity_OnCreate.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/5ace702ca7109b4f6ae08c35cce9ee84#file-mainactivity_oncreate-cs" class="Link--inTextBlock"><br />
          MainActivity_OnCreate.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Here I only initialize my view from layout, Activity&#8217;s private variables and instantiate user controls. Nothing more for this simple example.</p>
<h3>OnStart</h3>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45611494" 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_onstart-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_OnStart.cs content, created by dsibinski on 05:56PM on March 11, 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_OnStart.cs">
<tr>
<td id="file-mainactivity_onstart-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_onstart-cs-LC1" class="blob-code blob-code-inner js-file-line">protected override void OnStart()</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_onstart-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_onstart-cs-LC3" class="blob-code blob-code-inner js-file-line">    base.OnStart();</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_onstart-cs-LC4" class="blob-code blob-code-inner js-file-line">    RefreshUserInputsFromVariables();</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_onstart-cs-LC5" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_onstart-cs-LC6" class="blob-code blob-code-inner js-file-line">// &#8230;</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_onstart-cs-LC7" class="blob-code blob-code-inner js-file-line">private void RefreshUserInputsFromVariables()</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_onstart-cs-LC8" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_onstart-cs-LC9" class="blob-code blob-code-inner js-file-line">    _inputAmount.SetText(_amount.ToString(CultureInfo.InvariantCulture), TextView.BufferType.Editable);</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_onstart-cs-LC10" class="blob-code blob-code-inner js-file-line">    _txtResultDecimal.SetText(_result.ToString(CultureInfo.InvariantCulture), TextView.BufferType.Editable);</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-mainactivity_onstart-cs-LC11" class="blob-code blob-code-inner js-file-line">    _inputNumberOfPeople.SetText(_numberOfPeople.ToString(CultureInfo.InvariantCulture),</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-mainactivity_onstart-cs-LC12" class="blob-code blob-code-inner js-file-line">        TextView.BufferType.Editable);</td>
</tr>
<tr>
<td id="file-mainactivity_onstart-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-mainactivity_onstart-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/f5b27956b31e09db96167eeca264ee8a/raw/27d5ba3b21973ac87435bb671966bfce121567a2/MainActivity_OnStart.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/f5b27956b31e09db96167eeca264ee8a#file-mainactivity_onstart-cs" class="Link--inTextBlock"><br />
          MainActivity_OnStart.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In <em>OnStart()</em> method I just refresh UI elements &#8211; in that case initialize their <em>Text</em> properties with values stored in private variables.</p>
<h3>OnResume</h3>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45611550" 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_onresume-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_OnResume.cs content, created by dsibinski on 05:59PM on March 11, 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_OnResume.cs">
<tr>
<td id="file-mainactivity_onresume-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_onresume-cs-LC1" class="blob-code blob-code-inner js-file-line">protected override void OnResume()</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_onresume-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_onresume-cs-LC3" class="blob-code blob-code-inner js-file-line">    base.OnResume();</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_onresume-cs-LC4" class="blob-code blob-code-inner js-file-line">    InitializeUserControlsEvents();</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_onresume-cs-LC5" class="blob-code blob-code-inner js-file-line">    // TODO: retrieving variables (amount, number of people) from persistent storage (file, database)</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_onresume-cs-LC6" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_onresume-cs-LC7" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_onresume-cs-LC8" class="blob-code blob-code-inner js-file-line">// &#8230;</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_onresume-cs-LC9" class="blob-code blob-code-inner js-file-line">private void InitializeUserControlsEvents()</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_onresume-cs-LC10" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-mainactivity_onresume-cs-LC11" class="blob-code blob-code-inner js-file-line">    _btnCalculate.Click += _btnCalculate_Click;</td>
</tr>
<tr>
<td id="file-mainactivity_onresume-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-mainactivity_onresume-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/543cdbccbb0e28c144d15548db8b9e6f/raw/479a1e85703fa5680d62daee5acbd2187da89e76/MainActivity_OnResume.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/543cdbccbb0e28c144d15548db8b9e6f#file-mainactivity_onresume-cs" class="Link--inTextBlock"><br />
          MainActivity_OnResume.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>As we know, <em>OnResume</em> method is called every time our Activity is brought to the top of Activities stack (either after <em>OnCreate -&gt; OnStart</em> or when revealing it after being backgrounded). That&#8217;s a very good place to initialize dependencies to external services (e.g. open communication with DB or remote service). In my case, I just subscribed to <em>Click</em> events of the button. If I had any persistent storage present (for instance local DB) I would in this place retrieve recently saved values from it to my Activity&#8217;s variables to restore its state (<em>OnResume</em> might be called when Activity class&#8217;s state is already cleaned up).</p>
<h3>OnPause</h3>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist45611682" 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_onpause-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_OnPause.cs content, created by dsibinski on 06:05PM on March 11, 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_OnPause.cs">
<tr>
<td id="file-mainactivity_onpause-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-mainactivity_onpause-cs-LC1" class="blob-code blob-code-inner js-file-line">protected override void OnPause()</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-mainactivity_onpause-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-mainactivity_onpause-cs-LC3" class="blob-code blob-code-inner js-file-line">    base.OnPause();</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-mainactivity_onpause-cs-LC4" class="blob-code blob-code-inner js-file-line">    DetatchUserControlsEvents();</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-mainactivity_onpause-cs-LC5" class="blob-code blob-code-inner js-file-line">    // TODO: saving variables (amount, number of people) to persistent storage (file, database)</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-mainactivity_onpause-cs-LC6" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-mainactivity_onpause-cs-LC7" class="blob-code blob-code-inner js-file-line">// &#8230;</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-mainactivity_onpause-cs-LC8" class="blob-code blob-code-inner js-file-line">private void DetatchUserControlsEvents()</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-mainactivity_onpause-cs-LC9" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-mainactivity_onpause-cs-LC10" class="blob-code blob-code-inner js-file-line">    _btnCalculate.Click -= _btnCalculate_Click;</td>
</tr>
<tr>
<td id="file-mainactivity_onpause-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-mainactivity_onpause-cs-LC11" 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/3c2715968ecf87822ee6f79a46a553ac/raw/7002c8439f39510b30d5a7c4d7a2a60a085d4a98/MainActivity_OnPause.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/3c2715968ecf87822ee6f79a46a553ac#file-mainactivity_onpause-cs" class="Link--inTextBlock"><br />
          MainActivity_OnPause.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In <em>OnPause</em> method I need to be consistent with what I do in <em>OnResume</em> &#8211; when my app is taken to the background, I don&#8217;t need to wait for my button&#8217;s click events anymore, so let&#8217;s detach from it (maybe button&#8217;s <em>Click</em> event is not the best example here, but it&#8217;s just to visualize the purpose of the method). When my app is <em>resumed</em>, we will subscribe to this event again. Again, if I had any persistent storage, I&#8217;d save all variables&#8217; (which are necessary for restoring Activity&#8217;s state) values here to this storage, so they are able to be retrieved back as soon as <em>OnResume</em> is called.</p>
<h3>OnStop &amp; OnDestroy</h3>
<p>I didn&#8217;t implement those two methods in my app, it&#8217;s too simple to need anything in those places.</p>
<p>I deployed the app, attached with debugger and checked the order of methods&#8217; calls &#8211; all of them were called as described in previous paragraph.</p>
<h2>Summary</h2>
<p>It&#8217;s vital to understand how Android Activities and their states work. Even though it seems to be Android-specific, I&#8217;d rather say such approach is reasonable and even required by hardware on which mobile apps run (BTW, <a href="https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Art/high_level_flow_2x.png" target="_blank" rel="noopener">similar states seem to exist in iOS apps</a>).</p>
<p>When building Android app we need to think about Activities, especially make sure that each Activity in our application properly implements necessary lifecycle methods.</p>
<p><em><span style="text-decoration: underline;"><strong>Do you have or know any best practices while working with Activities and managing their lifecycle?</strong></span></em> I&#8217;d appreciate if you share it in the comments <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>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/xamarin-android-activities/">Xamarin – Android Activities</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/xamarin-android-activities/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">405</post-id>	</item>
		<item>
		<title>Hello Xamarin World &#8211; first steps</title>
		<link>https://www.codejourney.net/hello-xamarin-world-first-steps/</link>
					<comments>https://www.codejourney.net/hello-xamarin-world-first-steps/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 04 Mar 2017 23:12:14 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=244</guid>

					<description><![CDATA[<p>This time I want to say “Hello” to Xamarin world. First thing that needs to be done before starting Xamarin development, is obviously the installation of all necessary components. In this post I want to share my feelings about the installation (not without issues of course), configuration of my Xamarin Android solution and deployment process to&#8230;</p>
<p>The post <a href="https://www.codejourney.net/hello-xamarin-world-first-steps/">Hello Xamarin World &#8211; first steps</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p style="text-align: left;">This time I want to say “Hello” to Xamarin world.</p>
<p style="text-align: left;">First thing that needs to be done before starting Xamarin development, is obviously the installation of all necessary components.</p>
<p style="text-align: left;">In this post I want to share my feelings about the installation (not without issues of course), configuration of my Xamarin Android solution and deployment process to the device.<br />
<span id="more-244"></span></p>
<h2>Xamarin installation into Visual Studio 2015</h2>
<p style="text-align: left;">I’ve created my account at <a href="http://www.xamarin.com/" target="_blank" rel="noopener">xamarin.com</a>, logged in and chose <em>Download Xamarin for free</em> to download the installation package. There are generally two IDEs that can be used for Xamarin development: Visual Studio or Xamarin Studio. I’ve already had VS 2015 installed and decided I don’t want to explore a new IDE, so I downloaded installer for Visual Studio. What’s more, following Xamarin’s website, “Xamarin Studio is no longer included” in the Windows installer and they “encourage Windows developers to move to Visual Studio”. Well, that&#8217;s understandable, Microsoft acquired Xamarin, didn&#8217;t they? 😉</p>
<p style="text-align: left;"><em>BTW, when <a href="https://www.xamarin.com/download" target="_blank" rel="noopener">downloading Xamarin</a> I was obliged to fill the “Company” field – does anyone know why is that?</em></p>
<h2 style="text-align: left;"> Android SDK and emulator images size</h2>
<p style="text-align: left;">Interesting parts of the installation (if there could by any at all?) are Android Emulator installation which is then integrated into Visual Studio as well as Android SDK installation – fortunately it’s possible to change the location of Android SDK installation, because right after the setup it takes an enormous amount of disk space (with mandatory tools mentioned in the installation guide and two Android APIs):</p>
<p><figure id="attachment_323" aria-describedby="caption-attachment-323" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="323" data-permalink="https://www.codejourney.net/hello-xamarin-world-first-steps/android_sdk_size/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?fit=348%2C243&amp;ssl=1" data-orig-size="348,243" 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="android_sdk_size" data-image-description="&lt;p&gt;Android SDK size&lt;/p&gt;
" data-image-caption="&lt;p&gt;Android SDK size&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?fit=348%2C243&amp;ssl=1" class="wp-image-323 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?resize=300%2C209&#038;ssl=1" alt="Android SDK size - 41.6 GBs" width="300" height="209" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?resize=300%2C209&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?w=348&amp;ssl=1 348w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-323" class="wp-caption-text"><span style="font-size: 8pt;">Android SDK size</span></figcaption></figure></p>
<p style="text-align: left;">I’ve examined a bit more and it turns out that <strong>system images</strong> take the most of this space. Those are used only by emulators to be able to create a virtual device and debug on a simulator instead of deploying the app to a physical device every rime.</p>
<p style="text-align: left;">When I used to write some Android apps in Java and Android Studio long time ago, I found it very hard and complex to debug/test anything using emulator – it was simply very, very slow to load and work. This time I&#8217;ll see if emulator built in Visual Studio will do the job – if yes, why not using it ? I will of course also deploy directly to the device for tests, but it also takes time. I remember that when I wanted to test some small adjustments done “on the fly” (e.g. UI modifications/alignments) I dreamt about doing it quicker then deploying app to the phone every time. We’ll see, if emulator won’t do the job – I will clean up those folders.</p>
<h2 style="text-align: left;"> First issue in DSP</h2>
<p style="text-align: left;">I had to create a separate paragraph for that 🙂 Of course, it must have finally happened – first issue on my DSP way! Installation error, of course &#8211; <em>&#8220;Installation of &#8216;Xamarin&#8217; failed with more then one exception (attempt 3). It was not possible to complete an automatic installation.&#8221;</p>
<p></em></p>
<p style="text-align: left;">I expected the installation to terminate and evening spent on looking for a solution, exploring StackOverflow threads, but to my surprise a quite familiar-looking screen appeared explaining what to do next, i.e. how to install all the components manually. I had to download and install Java JDK, Android SDK and Xamarin.</p>
<p style="text-align: left;">After the next 30 minutes everything seemed to be installed. Just two last configuration steps in Visual Studio <a href="https://developer.xamarin.com/guides/android/getting_started/installation/windows/manual_installation/" target="_blank" rel="noopener">as described here.</a> Finally, to be able to run Android emulator Android Virtual Device Manager needs to be configured, <a href="https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/debug-on-emulator/android-sdk-emulator/#Configuring_Virtual_Devices" target="_blank" rel="noopener">as this tutorial describes</a>.</p>
<h2 style="text-align: left;">Android Solution Creation</h2>
<p style="text-align: left;">I cloned my <a href="https://github.com/dsibinski/MoneyBack" target="_blank" rel="noopener">Git repository</a>, opened Visual Studio and created <em>MoneyBack</em> solution 😉 I chose the project of type <em>Blank App (Android). </em>Here’s what VS produced:</p>
<p><figure id="attachment_358" aria-describedby="caption-attachment-358" style="width: 207px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="358" data-permalink="https://www.codejourney.net/hello-xamarin-world-first-steps/vs_android_xamarin_solution/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?fit=202%2C310&amp;ssl=1" data-orig-size="202,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="VS_Android_Xamarin_Solution" data-image-description="&lt;p&gt;VS Android Xamarin Solution&lt;/p&gt;
" data-image-caption="&lt;p&gt;VS Android Xamarin Solution&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?fit=202%2C310&amp;ssl=1" class=" wp-image-358" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?resize=207%2C318&#038;ssl=1" alt="VS Android Xamarin Solution" width="207" height="318" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?resize=195%2C300&amp;ssl=1 195w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?w=202&amp;ssl=1 202w" sizes="auto, (max-width: 207px) 100vw, 207px" /></a><figcaption id="caption-attachment-358" class="wp-caption-text"><span style="font-size: 8pt;">VS Android Xamarin Solution</span></figcaption></figure></p>
<p style="text-align: left;">Android Xamarin solution contains the following elements out-of-the-box:</p>
<ul>
<li><em>Properties<b> </b></em>– here <em>AssemblyInfo.cs</em> is probably well-known to all .NET developers (for the others: this file is .NET assembly’s metadata file, containing basic data about our application, like its name, version, company etc.), but there is also <em>AndroidManifest.xml, </em>which contains details and requirements for Android application, e.g. app’s name, supported SDKs versions numbers and required permissions for which the end user is asked when installing the app</li>
<li><em>References</em> – contains other assemblies required for the application to build; in case of Xamarin Android solution, it references both .NET assemblies like <em>System</em> or <em>System.Core</em> and <em>Mono.Android </em>assembly</li>
<li><em>Components</em> – stores Xamarin development packages that can be retrieved from <a href="https://components.xamarin.com/" target="_blank" rel="noopener">Components Store</a> (something like Xamarin-specific <em>Nuget</em>, I guess 😉 )</li>
<li><em>Assets</em> – allows to store additional files needed by the app (e.g. text files) available easily from the code</li>
<li><em>Resources</em><strong> – </strong>contains strings, images and layouts of the application</li>
</ul>
<h2>MainActivity</h2>
<p style="text-align: left;">Apart from above-mentioned folders, solution contains an <em>Activity </em>class (<em>MainActivity.cs</em>) which is decorated with <em>ActivityAttribute</em>:</p>
<pre><pre class="brush: csharp; title: ; notranslate">&#x5B;Activity(Label = &quot;MoneyBack&quot;, MainLauncher = true, Icon = &quot;@drawable/icon&quot;)]</pre>
<p style="text-align: left;">We&#8217;ll get into details of <em>activities</em> soon. For now, let&#8217;s just assume that:</p>
<pre><pre class="brush: csharp; title: ; notranslate">MainLauncher = true</pre>
<p style="text-align: left;">means that this class is the starting point of the application. It contains only one method:</p>
<pre><pre class="brush: csharp; title: ; notranslate">
protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);

   // Set our view from the &quot;main&quot; layout resource
   SetContentView (Resource.Layout.Main);

}</pre>
<p style="text-align: left;">Again, we’ll dive into <a href="https://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/" target="_blank" rel="noopener">Android activity’s lifecycle</a> very soon, but we can already imagine that “OnCreate” method is called when the activity is created.</p>
<h2>MoneyBack on the phone</h2>
<p style="text-align: left;">I plugged my Huawei P8 to the laptop, hit F5 and hoped to see my app running on the device. Instead, two components were installed first as separate apps &#8211; <em>Mono Shared Runtime</em> and <em>Xamarin.Android API-25</em>. Those two are used in debug build mode to allow debugging stuff. It would be fine if I didn&#8217;t have to re-plug my phone after installation of each of these two, as phone was doing nothing after.</p>
<p style="text-align: left;"> Finally,  <em>MoneyBack</em> appeared on Huawei&#8217;s screen with sad, black empty canvas. I added some well-known sentence to become a real Xamarin-newbie:</p>
<p><figure id="attachment_384" aria-describedby="caption-attachment-384" style="width: 182px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="384" data-permalink="https://www.codejourney.net/hello-xamarin-world-first-steps/moneyback_helloworld_xamarin/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?fit=201%2C354&amp;ssl=1" data-orig-size="201,354" 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_HelloWorld_Xamarin" data-image-description="&lt;p&gt;MoneyBack &amp;#8211; Hello world deployed to the phone&lt;/p&gt;
" data-image-caption="&lt;p&gt;MoneyBack &amp;#8211; Hello world deployed to the phone&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?fit=201%2C354&amp;ssl=1" class="wp-image-384" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?resize=182%2C321&#038;ssl=1" alt="MoneyBack - Hello world deployed to the phone" width="182" height="321" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?resize=170%2C300&amp;ssl=1 170w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?w=201&amp;ssl=1 201w" sizes="auto, (max-width: 182px) 100vw, 182px" /></a><figcaption id="caption-attachment-384" class="wp-caption-text"><span style="font-size: 8pt;">MoneyBack &#8211; Hello world deployed to the phone</span></figcaption></figure></p>
<h2>MoneyBack on the emulator</h2>
<p style="text-align: left;">I couldn’t initially manage to deploy my application to Android Emulator device. I tried creating few emulator devices – firstly I had issues with very strange resolution on the emulated device, then I created another one and when I tried to deploy on it I got an error saying “2&gt;Emulator is not ready to be used”. What I came up to is creating new Android Emulator Device, trying to start it (without deployment) and having “android” text on the device’s screen for the last 20 minutes. Then I found <a href="https://developer.xamarin.com/guides/android/getting_started/installation/accelerating_android_emulators/" target="_blank" rel="noopener">this emulation acceleration guide</a>, so I installed HAXM and it helped <strong>A LOT</strong>. Emulator is now starting within 30 seconds and I managed to deploy my app on it. Cool.</p>
<h2 style="text-align: left;">Summary</h2>
<p style="text-align: left;">Automatic installation of Xamarin on Windows with Visual Studio didn’t work, so I had to install all the packages manually, however it wasn’t problematic. Deployment to the phone was OK, but the installation of two additional components (<em>Mono Shared Runtime</em> and <em>Xamarin.Android API</em>) forced me to re-plug the device twice. I hope I won’t have this case very often, because if every deployment looks like that I’ll never finish this app…</p>
<p style="text-align: left;">I recommend everyone who wants to work with Android device emulator <a href="https://developer.xamarin.com/guides/android/getting_started/installation/accelerating_android_emulators/" target="_blank" rel="noopener">installing HAXM</a> &#8211; it really boosts the emulation.</p>
<div class="post">
<div class="body">
<div id="c4c4c9b5-cfa2-4848-a5d1-af794b4279f7" class="postBody" style="margin: 4px 0px 0px; border-width: 0px; padding: 0px;" contenteditable="true">
<p style="text-align: left;">Get ready for a deep dive into Xamarin soon 😎</p>
</div>
</div>
</div>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/hello-xamarin-world-first-steps/">Hello Xamarin World &#8211; first steps</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/hello-xamarin-world-first-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">244</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>
