<?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>Programming Archives - CodeJourney.net</title>
	<atom:link href="https://www.codejourney.net/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codejourney.net/category/programming/</link>
	<description>Become a better .NET full stack web developer</description>
	<lastBuildDate>Sun, 26 Jan 2025 17:36:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</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>Programming Archives - CodeJourney.net</title>
	<link>https://www.codejourney.net/category/programming/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">123174533</site>	<item>
		<title>Real .NET Interview Questions (2024/2025)</title>
		<link>https://www.codejourney.net/real-net-interview-questions-2024-2025/</link>
					<comments>https://www.codejourney.net/real-net-interview-questions-2024-2025/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 03 Dec 2024 16:16:31 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4909</guid>

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



<p>If you&#8217;re interested in knowing something about programming job search in current market conditions, feel free to leave a comment <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/real-net-interview-questions-2024-2025/">Real .NET Interview Questions (2024/2025)</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/real-net-interview-questions-2024-2025/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4909</post-id>	</item>
		<item>
		<title>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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-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-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-medium-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-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-medium-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-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-medium-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-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-medium-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-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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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">  <span class=pl-en>test</span><span class=pl-kos>(</span><span class=pl-s>&quot;should apply 10% discount if there are exactly 5 business class tickets&quot;</span><span class=pl-kos>,</span> <span class=pl-kos>(</span><span class=pl-kos>)</span> <span class=pl-c1>=&gt;</span> <span class=pl-kos>{</span></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">    <span class=pl-k>const</span> <span class=pl-s1>tickets</span> <span class=pl-c1>=</span> <span class=pl-v>Array</span><span class=pl-kos>.</span><span class=pl-en>from</span><span class=pl-kos>(</span><span class=pl-kos>{</span> <span class=pl-c1>length</span>: <span class=pl-c1>5</span> <span class=pl-kos>}</span><span class=pl-kos>,</span> <span class=pl-kos>(</span><span class=pl-kos>)</span> <span class=pl-c1>=&gt;</span> <span class=pl-kos>(</span><span class=pl-kos>{</span></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">      <span class=pl-c1>price</span>: <span class=pl-c1>10</span><span class=pl-kos>,</span></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">      <span class=pl-c1>isBusinessClass</span>: <span class=pl-c1>true</span><span class=pl-kos>,</span></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">    <span class=pl-kos>}</span><span class=pl-kos>)</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">    <span class=pl-k>const</span> <span class=pl-s1>totalPrice</span> <span class=pl-c1>=</span> <span class=pl-s1>calculator</span><span class=pl-kos>.</span><span class=pl-en>calculateTotalTicketsPrice</span><span class=pl-kos>(</span><span class=pl-s1>tickets</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">    <span class=pl-en>expect</span><span class=pl-kos>(</span><span class=pl-s1>totalPrice</span><span class=pl-kos>)</span><span class=pl-kos>.</span><span class=pl-en>toBe</span><span class=pl-kos>(</span><span class=pl-c1>45</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// 10% discount</span></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">  <span class=pl-kos>}</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/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-medium-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-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-medium-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-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-medium-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-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>5 Reasons To Not Use C# IDE For TypeScript Development</title>
		<link>https://www.codejourney.net/5-reasons-to-not-use-c-ide-for-typescript-development/</link>
					<comments>https://www.codejourney.net/5-reasons-to-not-use-c-ide-for-typescript-development/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 07:12:15 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[rider]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[visual studio code]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4684</guid>

					<description><![CDATA[<p>I know a few fellow devs who still use Visual Studio or Rider as their IDE for Typescript. If you&#8217;re one of them, this is going to be a little rant on you all 😄 In this short article, I will give you my 5 reasons why the backend code editor might not be the&#8230;</p>
<p>The post <a href="https://www.codejourney.net/5-reasons-to-not-use-c-ide-for-typescript-development/">5 Reasons To Not Use C# IDE For TypeScript Development</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I know a few fellow devs who still use Visual Studio or Rider as their IDE for Typescript. If you&#8217;re one of them, this is going to be a little rant on you all <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f604.png" alt="😄" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<p>In this short article, I will give you my 5 reasons why the backend code editor might not be the best IDE for frontend development <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>NOTE: calling this post a &#8220;rant&#8221; is obviously humorous <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;" /> This article is my own opinion, not a hate on anyone using different IDEs than I do.</em></p>



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



<h2 class="wp-block-heading">1. Rider and Visual Studio are slow</h2>



<p>While I consider Rider much faster than Visual Studio, even the JetBrains editor is too heavy for TypeScript development. Both of these apps are not good candidates for an IDE for TypeScript. They were designed to work with complex, backend solutions. These IDEs include a lot of features by default that can&#8217;t be turned off, most of which are not needed when working with frontend code.</p>



<p>This gets even worse if the solution you open contains both backend C# project and React app&#8217;s code, as it is in <a href="https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022">Visual Studio&#8217;s .NET+React template</a>. With time, even loading such a solution takes a lot of time. Especially if you use Visual Studio with <a href="https://www.jetbrains.com/resharper">ReSharper</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f648.png" alt="🙈" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">2. Less IntelliSense and tooling support</h2>



<p>From my experience, Visual Studio doesn&#8217;t show as much <a href="https://en.wikipedia.org/wiki/Intelligent_code_completion">IntelliSense info</a> as, for instance, Visual Studio Code does. The navigation in TypeScript code doesn&#8217;t feel as smooth as it should. </p>



<p>When I tried to use Rider or Visual Studio as IDE for TypeScript, I had issues working with popular frontend tooling like <a href="https://prettier.io/">Prettier</a> and <a href="https://eslint.org/">ESLint</a>. Theoretically, there are plugins for both of these IDEs, but in my experience they don&#8217;t always work properly. For instance, the &#8220;Format on save&#8221; feature of Prettier often doesn&#8217;t work in Rider for me. ESLint makes Visual Studio even slower (is that even possible?! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" />).</p>



<p>It&#8217;s hard to fully explain if you only worked with TypeScript in Rider or Visual Studio, but I promise you that switching to VS Code makes a huge difference <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Read on to get to know why!</p>



<h2 class="wp-block-heading">3. Confusion of concepts</h2>



<p>Let me explain my approach to frontend and backend first. To me, as a full stack developer, working on a frontend app requires a different mindset than working on backend. For instance, developing a React app requires me to think <em>The React Way</em> (we discussed it already in an article about <a href="https://www.codejourney.net/react-state-management-basics/">React state management</a>).</p>



<p>In my view, editing both frontend and backend code in the same editor makes you confuse concepts. If you learned JavaScript/TypeScript after working with C# for some time, you probably experienced trying to use <code>let</code> in C# or declaring C# types with colon (<code>:</code>) <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> But this is only a tip of the iceberg.</p>



<p>I think having a separate IDE for TypeScript makes you nicely switch context when working on the frontend app. Opening my TypeScript code editor, I immediately start <em>thinking in frontend</em>. It instantly switches my approach to writing code. I somehow start to behave like a frontend developer, not a full stack one. </p>



<p>I think such approach is beneficial. For instance, it lets me work on my frontend code as I would be a real consumer of the backend API, not the person who can implement the backend in whichever way I want. Thanks to that <em>switching of viewpoint</em>, I can focus on designing my frontend code properly, without worrying about the backend.</p>



<p>I also tend to make less assumptions like <em>oh no worries, I will do it on the server</em>. At that moment, with my IDE for TypeScript open, I am a frontend developer. It often leads to better API design later on, because I don&#8217;t make any assumptions about the backend. Working on a frontend part of the app, I usually use API mocks first, knowing only the shape of data that should come from the API. Only later, when I&#8217;m done with the frontend part, I switch to Rider to actually implement the API.</p>



<p>Of course, this can also work the other way around. You can first work on the backend, design your API according to the best practices (again &#8211; without even thinking about your frontend app) and finally switch to the frontend IDE, build the UI and consume the API instead of using mock in the first place.</p>



<p>I hope you got what I mean here, but it&#8217;s not easy to clearly explain <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">4. Temptation to sneak C# concepts to TS</h2>



<p>This point is a consequence of the previous one.  If your IDE for TypeScript is the same as your C# code editor, you will be tempted to sneak C# concepts into TypeScript. I often see .NET developers entering TypeScript world using <code>var</code> by default (which is kinda deprecated in JavaScript and considered a bad practice today) or enforcing C# brackets formatting style in their frontend code. I also noticed overuse of classes and inheritance in TypeScript, as well as confusing passing value/reference data directly into components instead of properly using <a href="https://www.codejourney.net/react-state-management-basics/"><code>state</code> and <code>props</code> in React</a>.</p>



<p>To sum it up: isolating yourself as a frontend developer by using a TypeScript-specific IDE (like VS Code) will help you learn good frontend practices quicker <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">5. Because VS Code is better <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;" /></h2>



<p>Last, but not least: the main reason to not use <a href="https://visualstudio.microsoft.com/">Visual Studio</a> or <a href="https://www.jetbrains.com/rider/">Rider</a> for TypeScript development is simple: <strong><a href="https://code.visualstudio.com/">Visual Studio Code</a> is better!</strong> <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;" /></p>



<p>VS Code is industry standard for frontend development today. According to <a href="https://survey.stackoverflow.co/2023/#section-most-popular-technologies-integrated-development-environment">Stack Overflow Developer Survey 2023</a>, over 70% of all developers use Visual Studio Code:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="928" height="340" data-attachment-id="4695" data-permalink="https://www.codejourney.net/5-reasons-to-not-use-c-ide-for-typescript-development/stack-overflow-survey-2023-vs-code/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/11/stack-overflow-survey-2023-vs-code.png?fit=928%2C340&amp;ssl=1" data-orig-size="928,340" 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-overflow-survey-2023-vs-code" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/11/stack-overflow-survey-2023-vs-code.png?fit=928%2C340&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/11/stack-overflow-survey-2023-vs-code.png?fit=928%2C340&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/11/stack-overflow-survey-2023-vs-code.png?resize=928%2C340&#038;ssl=1" alt="Visual Studio Code is the most widely used IDE for TypeScript (and IDE in general)" class="wp-image-4695" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/11/stack-overflow-survey-2023-vs-code.png?w=928&amp;ssl=1 928w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/11/stack-overflow-survey-2023-vs-code.png?resize=768%2C281&amp;ssl=1 768w" sizes="auto, (max-width: 928px) 100vw, 928px" /></figure>
</div>


<p></p>



<p>VS Code is lightweight. It doesn&#8217;t have all heavy features included by default. If you want something additional, it must be installed as an extension. By the way, the extensions are really great and actively developed by the community.</p>



<p>VS Code is mostly written in TypeScript, which makes is somewhat designed for TypeScript. It has great search features, awesome IntelliSense for TypeScript and works really fast. Especially compared to Visual Studio or even Rider.</p>



<p>Visual Studio Code can also be run on any platform. It even has a <a href="https://vscode.dev/">fully-featured web version</a>. The IDE is also completely free and open-source.</p>



<p>I think I won&#8217;t continue listing numerous advantages of VS Code here. If you&#8217;re reading this, and you are still not encouraged to switch to VS Code for TypeScript development, please give it a try <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 another try if you already tried, but it didn&#8217;t click. This time, first <a href="https://www.youtube.com/playlist?list=PLj6YeMhvp2S5UgiQnBfvD7XgOMKs3O_G6">watch some introductory videos</a> with tips on how to get started and get the most of the editor. You can also check the <a href="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/">VS Code extensions I use on a daily basis</a> to make your work with this editor easier.</p>



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



<p>That&#8217;s it! I really wanted to write this article one day. Do you know that feeling when you learned something new or made significant progress in some area of your life, and you see people still struggling with what you have overcome? It&#8217;s this moment when you would really love to give these people all of your knowledge and make them magically change their lives &#8211; the same way you did <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;" /> I feel exactly that when I see fellow developers struggling (it&#8217;s a matter of opinion, I know <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;" />) with Typescript in Visual Studio <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f648.png" alt="🙈" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>I know I can&#8217;t change you and your beliefs and I don&#8217;t want to do that. But the great thing is that I can share my point of view and try to encourage you to alter yours a little. At least try and let me know what are your thoughts on 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>Also, if you&#8217;re a frontend or full stack developer working in a backend IDE like Rider or Visual Studio, let me know why! I&#8217;m really curious. Did you try VS Code? If yes, what didn&#8217;t fit?</p>
<p>The post <a href="https://www.codejourney.net/5-reasons-to-not-use-c-ide-for-typescript-development/">5 Reasons To Not Use C# IDE For TypeScript Development</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/5-reasons-to-not-use-c-ide-for-typescript-development/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4684</post-id>	</item>
		<item>
		<title>React State Management Basics</title>
		<link>https://www.codejourney.net/react-state-management-basics/</link>
					<comments>https://www.codejourney.net/react-state-management-basics/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 29 Oct 2023 04:39:10 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[react]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4591</guid>

					<description><![CDATA[<p>If I were to point out a single concept that is critical to understand in React development, it would be state management. So what is React state management? How is it different from managing data in C# or Java? Let&#8217;s find out! 🙂 State If you are a backend or desktop developer, you may have&#8230;</p>
<p>The post <a href="https://www.codejourney.net/react-state-management-basics/">React State Management Basics</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If I were to point out a single concept that is critical to understand in React development, it would be state management.</p>



<p>So what is React state management? How is it different from managing data in C# or Java? Let&#8217;s find out! <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-4591"></span>



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



<p>If you are a backend or desktop developer, you may have never come across the term of state. At least, I never used it before learning frontend web development. Surely not in the context it is used in frameworks like React. The term more familiar to me at that time was <em>data binding</em> known from <a href="https://learn.microsoft.com/en-us/dotnet/desktop/wpf/overview">WPF</a> or <a href="https://learn.microsoft.com/en-us/dotnet/desktop/winforms/overview">WinForms</a>.</p>



<p>This is what <a href="https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data">WPF documentation</a> says:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>
<cite>Data binding is the process that establishes a connection between the app UI and the data it displays. If the binding has the correct settings and the data provides the proper notifications, when the data changes its value, the elements that are bound to the data reflect changes automatically</cite></blockquote>



<p>In case of WPF, the crucial part to me is <em><strong>If the binding has the correct settings and the data provides the proper notifications</strong></em> <strong><em>(&#8230;)</em></strong>. If you have ever worked with WPF, you know how frustrating can these <em>notifications</em> be (any <code>INotifyPropertyChanged</code> fans here?).</p>



<p>WPF&#8217;s state management it not that bad. However, React has something better <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>React introduces us to a concept of <em>state</em>. In React components, you do not set anything directly, like calling some code to update an input&#8217;s value (this is possible, we&#8217;re still in <a href="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/">JavaScript world</a>, but it&#8217;s not a <em>React way</em> of doing stuff). You don&#8217;t directly bind your UI controls with data like you would in WPF or WinForms. Instead, you keep the data in memory, which is a current <em>state </em>of the UI (the whole app or a piece of it). </p>



<p><strong>When the state changes, your UI is updated by React</strong>. In other words &#8211; <strong>in React, UI is a function of state</strong>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-markup code-embed-pre"  data-start="1" data-line-offset="0"><code class="language-markup code-embed-code">UI = fn(state)</code></pre> <div class="code-embed-infos"> </div> </div></div>



<p>It means that your React app (or its individual pieces called <em>components</em>) take some state and output the actual, rendered UI.</p>



<p>This is React state management in a nutshell. Let&#8217;s explore it a bit more <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>Small disclaimer:</em> <em>I will focus on state in React functional componets. I consider <a href="https://react.dev/reference/react/Component">class components somewhat legacy</a>. I think this meme summarizes it best <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;" />:</em></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.freecodecamp.org/news/functional-setstate-is-the-future-of-react-374f30401b6b/"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="381" data-attachment-id="4669" data-permalink="https://www.codejourney.net/react-state-management-basics/react-setstate-meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/react-setstate-meme.jpg?fit=500%2C381&amp;ssl=1" data-orig-size="500,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="react-setstate-meme" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/react-setstate-meme.jpg?fit=500%2C381&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/react-setstate-meme.jpg?fit=500%2C381&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/react-setstate-meme.jpg?resize=500%2C381&#038;ssl=1" alt="" class="wp-image-4669"/></a></figure>
</div>


<h3 class="wp-block-heading">The Naive Way</h3>



<p>Let&#8217;s try to approach React state management as C# developer. In React, the basic piece of UI we create is a component. Let&#8217;s add one:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">import Button from &quot;react-bootstrap/Button&quot;;<br/><br/>export const NaiveComponent = () =&gt; {<br/>  return (<br/>    &lt;&gt;<br/>      &lt;div&gt;I am a naive component&lt;/div&gt;<br/>      &lt;Button variant=&quot;success&quot;&gt;Click me!&lt;/Button&gt;<br/>    &lt;/&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">NaiveComponent.tsx</span> </div> </div></div>



<p>For now, we render some text and a button which does nothing. What we want is to have some data displayed, like a number, which is incremented on every button click. Let&#8217;s try to implement that naively:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const NaiveComponent = () =&gt; {<br/>  let myCount = 0;<br/><br/>  return (<br/>    &lt;&gt;<br/>      &lt;div&gt;I am a naive component&lt;/div&gt;<br/>      &lt;div&gt;Current count: {myCount}&lt;/div&gt;<br/>      &lt;Button<br/>        variant=&quot;success&quot;<br/>        onClick={() =&gt; {<br/>          myCount＋＋;<br/>        }}<br/>      &gt;<br/>        Click me!<br/>      &lt;/Button&gt;<br/>    &lt;/&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">NaiveComponent.tsx &#8211; the naive counter incrementing</span> </div> </div></div>



<p>Now, let&#8217;s check if it works:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="536" height="285" data-attachment-id="4602" data-permalink="https://www.codejourney.net/react-state-management-basics/chrome_wkzlxfcktf/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_wkZlXfCKTf.gif?fit=536%2C285&amp;ssl=1" data-orig-size="536,285" 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="chrome_wkZlXfCKTf" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_wkZlXfCKTf.gif?fit=536%2C285&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_wkZlXfCKTf.gif?fit=536%2C285&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_wkZlXfCKTf.gif?resize=536%2C285&#038;ssl=1" alt="" class="wp-image-4602"/></figure>
</div>


<p></p>



<p>It looks nothing happens <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f979.png" alt="🥹" class="wp-smiley" style="height: 1em; max-height: 1em;" /> To investigate that, we can add a <code>console.log</code> (the most common debugging technique in JavaScript world <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" />) to the <code>onClick</code> event:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">onClick={() =&gt; {<br/>          myCount＋＋;<br/>          console.log(myCount);<br/>        }}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">onClick with console.log</span> </div> </div></div>



<p>How does that look in the console now?</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1071" height="591" data-attachment-id="4603" data-permalink="https://www.codejourney.net/react-state-management-basics/chrome_g62ao8n7fw/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_g62ao8n7FW.gif?fit=1071%2C591&amp;ssl=1" data-orig-size="1071,591" 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="chrome_g62ao8n7FW" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_g62ao8n7FW.gif?fit=1071%2C591&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_g62ao8n7FW.gif?fit=1071%2C591&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_g62ao8n7FW.gif?resize=1071%2C591&#038;ssl=1" alt="React state management - naive way (like C# dev), not working" class="wp-image-4603" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_g62ao8n7FW.gif?w=1071&amp;ssl=1 1071w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_g62ao8n7FW.gif?resize=768%2C424&amp;ssl=1 768w" sizes="auto, (max-width: 1071px) 100vw, 1071px" /></figure>
</div>


<p></p>



<p>Woooow, something is really going wrong here! The data is updated in memory, but not reflected in the UI <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>Why does that happen? Because <code>myCount</code> is not a state. It&#8217;s just some variable we created hoping that it will work fine as part of the UI. Remember what we have discussed in the previous section &#8211; we need to start <em>thinking in React</em>. This is <em>The</em> <em>React way</em>, not <em>Java way </em>or <em>C# way </em>anymore.</p>



<h3 class="wp-block-heading">The React Way</h3>



<p>So, how to use React state management properly in our example? We need to make <code>myCount</code> be a part of component&#8217;s state. The simplest way to do that looks as follows:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="2,11" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const TheReactWayComponent = () =&gt; {<br/>  const [myCount, setMyCount] = useState(0);<br/><br/>  return (<br/>    &lt;&gt;<br/>      &lt;div&gt;I am a React Way component&lt;/div&gt;<br/>      &lt;div&gt;Current count: {myCount}&lt;/div&gt;<br/>      &lt;Button<br/>        variant=&quot;success&quot;<br/>        onClick={() =&gt; {<br/>          setMyCount(myCount ＋ 1);<br/>        }}<br/>      &gt;<br/>        Click me!<br/>      &lt;/Button&gt;<br/>    &lt;/&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">TheReactWayComponent.tsx &#8211; The React Way</span> </div> </div></div>



<p>First, instead of declaring a &#8220;normal&#8221; variable for storing our UI-related data, we used the <code>useState</code> <a href="https://react.dev/reference/react#state-hooks">hook</a>. As you can see, it returns an array with two things: our state variable (<code>myCount) </code>and a function to update its value<code> </code>(<code>setMyCount</code>). We also set the initial value to <code>0</code>. A good practice is to always use a construct like <code>[myCount, setMyCount]</code> to destructure what <code>useState</code> returns into named, separate objects.</p>



<p>Now we are managing our component&#8217;s state <em>The React Way</em>. Does it work? Let&#8217;s see:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="464" height="215" data-attachment-id="4624" data-permalink="https://www.codejourney.net/react-state-management-basics/chrome_ojmhjudmmd/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_OJMhjuDMmd.gif?fit=464%2C215&amp;ssl=1" data-orig-size="464,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="chrome_OJMhjuDMmd" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_OJMhjuDMmd.gif?fit=464%2C215&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_OJMhjuDMmd.gif?fit=464%2C215&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_OJMhjuDMmd.gif?resize=464%2C215&#038;ssl=1" alt="React state management - The React Way" class="wp-image-4624"/></figure>
</div>


<p></p>



<p>Great! We have just learned how the basic form of state management works in React. That was easy, wasn&#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>Now, let us discuss one more aspect related to the state itself.</p>



<h3 class="wp-block-heading">Reference vs value</h3>



<p>We know the React Way for state management now. We feel confident. However, we are also used to how data is managed in C# or Java, especially in terms of <a href="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/">handling reference and value types</a>. This knowledge will come very handy now <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&#8217;s try to create a bit more complex component:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">type Person = {<br/>  id: number;<br/>  name: string;<br/>  age: number;<br/>};<br/><br/>export const ObjectHolderComponent = () =&gt; {<br/>  const johnInitialValue: Person = {<br/>    id: 1,<br/>    name: &quot;John Doe&quot;,<br/>    age: 30,<br/>  };<br/><br/>  const [john, setJohn] = useState&lt;Person&gt;(johnInitialValue);<br/><br/>  return (<br/>    &lt;&gt;<br/>      &lt;div&gt;ID: {john.id}&lt;/div&gt;<br/>      &lt;div&gt;Name: {john.name}&lt;/div&gt;<br/>      &lt;div&gt;Age: {john.age}&lt;/div&gt;<br/>      &lt;Button<br/>        variant=&quot;success&quot;<br/>        onClick={() =&gt; {<br/>          const currentJohnObject = john;<br/>          currentJohnObject.age = currentJohnObject.age ＋ 1;<br/>          console.log(currentJohnObject);<br/>          setJohn(currentJohnObject);<br/>        }}<br/>      &gt;<br/>        Make John older<br/>      &lt;/Button&gt;<br/>    &lt;/&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">ObjectHolderComponent.tsx</span> </div> </div></div>



<p>Now, instead of storing a single value in our component&#8217;s state, we store a whole object of type <code>Person</code>. The object has a few properties: <code>id</code>, <code>name</code> and <code>age</code>.</p>



<p>There is also a button. We want this button to take the current <code>john</code> object, increment the value of <code>age</code> on it and update the state. We do it The React Way using <code>setJohn</code> function returned by <code>useState</code>. Just to be sure, we also have the <code>console.log(john)</code> just before updating the state. Does that work as we expected?</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="873" height="656" data-attachment-id="4626" data-permalink="https://www.codejourney.net/react-state-management-basics/chrome_hlgfththbt/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_hlgFthtHBT.gif?fit=873%2C656&amp;ssl=1" data-orig-size="873,656" 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="chrome_hlgFthtHBT" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_hlgFthtHBT.gif?fit=873%2C656&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_hlgFthtHBT.gif?fit=873%2C656&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_hlgFthtHBT.gif?resize=873%2C656&#038;ssl=1" alt="Changing an object's (reference) internal variable does not trigger a re-render, even we use useState" class="wp-image-4626" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_hlgFthtHBT.gif?w=873&amp;ssl=1 873w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_hlgFthtHBT.gif?resize=768%2C577&amp;ssl=1 768w" sizes="auto, (max-width: 873px) 100vw, 873px" /></figure>
</div>


<p></p>



<p>Eh, what&#8217;s happening here this time? We can clearly see that <code>age</code> is updated on the object on each click, but why isn&#8217;t the UI re-rendered? <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>As I mentioned before, it&#8217;s critical to understand the difference between reference and value types here. If you don&#8217;t know it, <a href="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/">go and make up for it now</a>.</p>



<p>The reason it does not work is that we haven&#8217;t updated the actual content of <code>john</code> state variable by calling <code>setJohn(currentJohnObject)</code>. <strong>What is really being hold in <code>john</code> variable is the reference (pointer, address in memory) to the actual object</strong>. And this is what React tracks. We didn&#8217;t really update it, because we assigned the same instance of the object to the state. It doesn&#8217;t matter that we updated its internal property <code>age</code> &#8211; the reference itself wasn&#8217;t updated.</p>



<p>How do we solve that? Well, in current solution we&#8217;d need to create a copy of <code>john</code> object before using <code>setJohn</code> to alter the state. In effect, we&#8217;ll get a new instance of the object in memory and <code>john</code> variable will hold a new reference (address) to it.</p>



<p>So, if we only change our <code>onClick</code> implementation to this one:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">onClick={() =&gt; {<br/>          const johnCopy = { ...john };<br/>          johnCopy.age = john.age ＋ 1;<br/>          setJohn(johnCopy);<br/>        }}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">ObjectHolderComponent.tsx &#8211; onClick implementation with copying the original object</span> </div> </div></div>



<p>Everything starts to work as expected:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="333" height="236" data-attachment-id="4627" data-permalink="https://www.codejourney.net/react-state-management-basics/chrome_yfmhz6z0xn/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_yfmHz6z0Xn.gif?fit=333%2C236&amp;ssl=1" data-orig-size="333,236" 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="chrome_yfmHz6z0Xn" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_yfmHz6z0Xn.gif?fit=333%2C236&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_yfmHz6z0Xn.gif?fit=333%2C236&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/chrome_yfmHz6z0Xn.gif?resize=333%2C236&#038;ssl=1" alt="Changing a reference state by creating a copy of it works fine in React" class="wp-image-4627"/></figure>
</div>


<p></p>



<p>I think you now understand how React state management works. I also hope that you see the issues managing state in such a way can bring. Even in this trivial example, we create a new instance of an object on every button click. Apart from memory usage considerations, this just looks ugly. Imagine manually creating copies of much more complex objects, like classes storing arrays or dictionaries. This gets pretty wild <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>We will see how this issue can be addressed by the end of this article. But first, let&#8217;s discuss <code>props</code> &#8211; another concept critical to really understand React state management.</p>



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



<p>Apart from <code>state</code>, we also use <code>props</code> to control the state of our React components. The name is a short for <em>properties</em>, which quite well describes its purpose. <code>Props</code> are the data input provided to a component from outside (from a parent component). They are immutable and cannot be changed inside the component which receives them. Let&#8217;s see some examples.</p>



<h3 class="wp-block-heading">Sharing state between components</h3>



<p>The most common usage for <code>props</code> is sharing state between components. Imagine that you have an input, where the user manually enters some data. You want to use the current value of this input in two other components. This is where you need to share your component&#8217;s state (the value of the input) with these two other components. We often call it <em>lifting the state up</em> &#8211; you keep your state higher in the components tree, so the child components can use it.</p>



<p>Let&#8217;s try to see an example of connecting <code>state</code> with <code>props</code>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="4,9,27,28" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const PersonData = () =&gt; {<br/>  const minimumAge = 5;<br/>  const maximumAge = 100;<br/>  const [age, setAge] = useState&lt;number&gt;(minimumAge);<br/><br/>  const handleAgeChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br/>    const enteredAge = parseInt(event.target.value);<br/>    if (enteredAge &gt;= minimumAge &amp;&amp; enteredAge &lt;= maximumAge) {<br/>      setAge(enteredAge);<br/>    }<br/>  };<br/><br/>  return (<br/>    &lt;&gt;<br/>      &lt;Form&gt;<br/>        &lt;Form.Group controlId=&quot;age&quot;&gt;<br/>          &lt;Form.Label&gt;Your age&lt;/Form.Label&gt;<br/>          &lt;Form.Control<br/>            type=&quot;number&quot;<br/>            value={age}<br/>            onChange={handleAgeChange}<br/>            min={minimumAge}<br/>            max={maximumAge}<br/>          /&gt;<br/>        &lt;/Form.Group&gt;<br/>      &lt;/Form&gt;<br/>      &lt;DaysLiving currentAge={age} /&gt;<br/>      &lt;YearsUntilCentenarian currentAge={age} /&gt;<br/>    &lt;/&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">PersonData.tsx &#8211; state and props in practice</span> </div> </div></div>



<p>As you can see, at lines 4 and 9 we manage the state variable <code>age</code>. This is the old stuff we have already seen.</p>



<p>However, at lines 27 and 28 we are passing the <code>age</code> state variable into <code>DaysLiving</code> and <code>YearsUntilCentenarian</code> children components as <code>currentAge</code> prop. This is how the <code>DaysLiving</code> component is implemented:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">type DaysLivingProps = {<br/>  currentAge: number;<br/>};<br/><br/>export const DaysLiving = (props: DaysLivingProps) =&gt; {<br/>  const daysLived = props.currentAge * 365;<br/><br/>  return (<br/>    &lt;div&gt;<br/>      &lt;p&gt;You have lived for {daysLived} days.&lt;/p&gt;<br/>    &lt;/div&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">DaysLiving.tsx</span> </div> </div></div>



<p>Notice that <code>props</code> is simply a typed object you pass to a function component. To make things easier, you can also use object destructuring and accept the props in the following way:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const DaysLiving = ({currentAge}: DaysLivingProps) =&gt; {<br/>  const daysLived = currentAge * 365;<br/>  /// ... rest of the code</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">DaysLiving.tsx &#8211; props with object destructuring</span> </div> </div></div>



<p>That way, you don&#8217;t need to write <code>props.currentAge</code> every time you want to use this property inside the component.</p>



<h3 class="wp-block-heading">Does changing props always trigger a re-render?</h3>



<p>Well, generally the answer to this question is <em>yes</em>. Every time a prop of a component changes, this component will get re-rendered. However, this is not <em>entirely</em> true <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>To make this belief true, we need to assume that this prop is changed <em>in a React way</em>. So, to take things literally, consider this component we saw before:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const DaysLiving = ({currentAge}: DaysLivingProps) =&gt; {<br/>  const daysLived = currentAge * 365;<br/><br/>  return (<br/>    &lt;div&gt;<br/>      &lt;p&gt;You have lived for {daysLived} days.&lt;/p&gt;<br/>    &lt;/div&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">DaysLiving.tsx</span> </div> </div></div>



<p>From its perspective only, it accepts a <code>currentAge</code> property. For this component to re-render, it&#8217;s not enough that the <code>currentAge</code> property changes in any way. <strong>Its value must be changed by mutating the state in the parent component</strong>.</p>



<p>So, if the value provided as <code>currentAge</code> to <code>DaysLiving</code> component changes in the parent component by properly mutating the state (with <code>setAge</code> mutation callback, in our case):</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="7,14" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const PersonData = () =&gt; {<br/>  // ...<br/>  const [age, setAge] = useState&lt;number&gt;(minimumAge);<br/><br/>  const handleAgeChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br/>      // ...<br/>      setAge(enteredAge);<br/>    }<br/>  };<br/><br/>  return (<br/>    &lt;&gt;<br/>      // ...<br/>      &lt;DaysLiving currentAge={age} /&gt;<br/>      // ...<br/>    &lt;/&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">PersonData.tsx &#8211; mutating the state for children components</span> </div> </div></div>



<p>the child component (<code>DaysLiving</code>) will get re-rendered.</p>



<p>This is because when a parent component changes, React by default re-renders the parent component itself and all of its children.</p>



<p>If you modified the <code>age</code> variable in the parent compont directly, without using <code>setAge</code> (which we already know it&#8217;s incorrect), the <code>currentAge</code> prop would technically change, but the <code>DaysLiving</code> component will not get re-rendered.</p>



<h3 class="wp-block-heading">state vs props</h3>



<p>This is a question that people oftern ask: what&#8217;s the difference between <code>props</code> and <code>state</code> in React? <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>I would start with addressing this differently: what do <code>props</code> and <code>state</code> have in common?</p>



<p>As you already know, both are used for React state management. Both of them influence when the components will be re-rendered by React. Props and state are the absolute foundations of React.</p>



<p>The main difference is that <code>state</code> is used internally in a component, while <code>props</code> are used to pass information from parent to children components. <code>State</code> is also naturally mutable within a component where it&#8217;s defined, but <code>props</code> are immutable and cannot be changed in a component that receives and uses them.</p>



<h2 class="wp-block-heading">React state management libraries</h2>



<p>That&#8217;s basically everything you need to know to be able to comfortably work with React state management. However, I mentioned before that managing state using only built-in React mechanisms actually sucks <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> That&#8217;s why I&#8217;d like to make a short point on state management libraries.</p>



<p>Maybe you heard about <a href="https://redux.js.org/">Redux</a>, <a href="https://github.com/pmndrs/zustand">Zustand</a> or <a href="https://mobx.js.org/README.html">MobX</a>. All of them are state management libraires for React. But why would you even need one? And should you learn one now?</p>



<p>In my opinion, you can easily start working with React using the built-in state management mechanisms we discussed today. It&#8217;s good to know how it works in practice. However, the truth is that as your application grows and you want to keep it scalable and maintenable, you will need a state management library at some point. As soon as your components tree gets bigger, sharing data and state will not be as easy as &#8220;passing props to a children component&#8221;. You will need to share state between multiple components in the tree, sometimes not only between parent and children, but also with another components defined on the same level or even in a totally different place of the tree.</p>



<p>This is where React state management libraries come very handy. They solve many of the React&#8217;s issues that come to the surface as your state gets complex. But even if you use one, you will still always need <code>state</code> and <code>props</code>. That&#8217;s why it&#8217;s critical to understand these two basic concepts first and play with them for some time.</p>



<p>If you&#8217;re starting out, it&#8217;s good to know that state management libraries exist and that one day you will have to get your hands on one (or more <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;" />) of them. I hope to share my thoughts on state management libraries in a separate article one day.</p>



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



<p>That&#8217;s it! Now you should know how React manages state of its components. Of course, we didn&#8217;t cover everything related to state management in React, but I hope you got the basics <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 all of the source code used in this article <a href="https://github.com/dsibinski/codejourney/tree/main/react-state-management">here</a>.</p>



<p><strong>How do you manage state in your React apps? Do you use a state management library? If yes, which one and why? Let me know in the comments below!</strong></p>
<p>The post <a href="https://www.codejourney.net/react-state-management-basics/">React State Management Basics</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/react-state-management-basics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4591</post-id>	</item>
		<item>
		<title>TypeScript Compiler Explained</title>
		<link>https://www.codejourney.net/typescript-compiler-explained/</link>
					<comments>https://www.codejourney.net/typescript-compiler-explained/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 17 Oct 2023 04:08:05 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4530</guid>

					<description><![CDATA[<p>As a frontend developer, one of the things you should know is how TypeScript compiler works. Sooner or later you will work with this language (which I sincerely wish you!), so it&#8217;s good to know your stuff 😉 In this article, I will explain TypeScript compiler to you in simple terms. We will avoid complex&#8230;</p>
<p>The post <a href="https://www.codejourney.net/typescript-compiler-explained/">TypeScript Compiler Explained</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As a frontend developer, one of the things you should know is how TypeScript compiler works. Sooner or later you will work with this language (which I sincerely wish you!), so it&#8217;s good to know your stuff <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 this article, I will explain TypeScript compiler to you in simple terms. We will avoid complex stuff &#8211; only what you need for your everyday frontend developer&#8217;s work. We will not explore the inner workings of the TypeScript compiler Instead, we&#8217;ll see some practical implications of its workings for TypeScript developer. Let&#8217;s dive in <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-4530"></span>



<h2 class="wp-block-heading">Few basic facts about TypeScript</h2>



<p>For starters, let&#8217;s establish some quick facts about TypeScript as a language.</p>



<h3 class="wp-block-heading">TypeScript is a superset of JavaScript</h3>



<p>You may have heard that TypeScript is a superset of JavaScript. In other words, every JavaScript code is a valid TypeScript code. In  case of TypeScript, being a &#8220;superset&#8221; means adding types information on top of perfectly legit JavaScript code.</p>



<p>Why is TypeScript only adding its types on top of JavaScript? In order to be able to remove them easily <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 why would it do that?!</p>



<h3 class="wp-block-heading">Browser doesn&#8217;t understand TypeScript</h3>



<p>The answer is that TypeScript cannot be run directly by a web browser (or NodeJS).</p>



<p>Let&#8217;s take this trivial TypeScript code:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">let age : number = 27;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">Trivial TypeScript code</span> </div> </div></div>



<p>and try to paste it into Google Chrome&#8217;s console in order to execute it:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="438" height="145" data-attachment-id="4535" data-permalink="https://www.codejourney.net/typescript-compiler-explained/typescript-in-chrome-console/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/TypeScript-in-chrome-console.png?fit=438%2C145&amp;ssl=1" data-orig-size="438,145" 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-in-chrome-console" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/TypeScript-in-chrome-console.png?fit=438%2C145&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/TypeScript-in-chrome-console.png?fit=438%2C145&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/TypeScript-in-chrome-console.png?resize=438%2C145&#038;ssl=1" alt="TypeScript code cannot be understood by a web browser" class="wp-image-4535"/></figure>
</div>


<p></p>



<p>As you can see, it fails. The <code>number</code> type annotation is unknown to the browser. It means that <strong>before any TypeScript code is run in the browser, the information about types must be stripped out</strong>. In the end, browsers and NodeJS environments can only execute JavaScript. This is in short what TypeScript compiler does, and we&#8217;ll get into the details soon. For now, this leads us to another conclusion, that&#8230;</p>



<h3 class="wp-block-heading">TypeScript is for developers</h3>



<p>As we have just discovered, types must be removed by the TypeScript compiler before the code can be executed by the browser. In fact, this line of TypeScript:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">let age : number = 27;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">TypeScript code before compilation</span> </div> </div></div>



<p>produces the following JavaScript output when processed by the TypeScript compiler:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-javascript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-javascript code-embed-code">var age = 27;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">JavaScript code after TypeScript compilation</span> </div> </div></div>



<p>This is effectively the same code we wrote in TypeScript, but without type annotations.</p>



<p>Wrong data types assignments will only be detected at compile time:</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="576" height="241" data-attachment-id="4549" data-permalink="https://www.codejourney.net/typescript-compiler-explained/tsc-compilation-error/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/tsc-compilation-error.png?fit=576%2C241&amp;ssl=1" data-orig-size="576,241" 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="tsc-compilation-error" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/tsc-compilation-error.png?fit=576%2C241&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/tsc-compilation-error.png?fit=576%2C241&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/tsc-compilation-error.png?resize=576%2C241&#038;ssl=1" alt="" class="wp-image-4549"/></figure>



<p></p>



<p>but as soon as it&#8217;s compiled, this protection is not there anymore <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f937-200d-2642-fe0f.png" alt="🤷‍♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<p>This discovery means that <strong>TypeScript is for developers</strong>. Its job is to make our lives easier. Of course, in the end it also improves the end users&#8217; experience, because <a href="https://www.codejourney.net/is-it-worth-migrating-to-typescript/">programming in TypeScript is much better than using pure JS</a>. But you can already see that TypeScript it not present at runtime at all. It only protects us until the compilation step by static types checking.</p>



<p>The philosophy is more or less as follows <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;" />:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://anjulashanaka.medium.com/say-goodbye-to-runtime-errors-with-typescript-7afbae84e75f"><img data-recalc-dims="1" loading="lazy" decoding="async" width="602" height="333" data-attachment-id="4551" data-permalink="https://www.codejourney.net/typescript-compiler-explained/typescript-no-runtime-errors-if-code-does-not-compile-meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-no-runtime-errors-if-code-does-not-compile-meme.jpg?fit=602%2C333&amp;ssl=1" data-orig-size="602,333" 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;1&quot;}" data-image-title="typescript-no-runtime-errors-if-code-does-not-compile-meme" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-no-runtime-errors-if-code-does-not-compile-meme.jpg?fit=602%2C333&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-no-runtime-errors-if-code-does-not-compile-meme.jpg?fit=602%2C333&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-no-runtime-errors-if-code-does-not-compile-meme.jpg?resize=602%2C333&#038;ssl=1" alt="TypeScript compiler only protects you at runtime (during compilation)" class="wp-image-4551"/></a></figure>
</div>


<p></p>



<p>What&#8217;s worth mentioning, as the <a href="https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html">language&#8217;s specification</a> says, &#8220;TypeScript never changes the runtime behavior of JavaScript code&#8221;.</p>



<h2 class="wp-block-heading">TypeScript compiler in practice</h2>



<h3 class="wp-block-heading">tsc </h3>



<p>TypeScript compiler is actually a CLI tool called <code>tsc</code>. It can be installed globally on your machine and used directly or built into your IDE. Refer to <a href="https://www.typescriptlang.org/download">official documentation</a> for installation details.</p>



<p>The compiler can also be installed locally in your project. It can then be set up as part of the build pipeline, which is supported by many <a href="https://www.codejourney.net/what-is-a-javascript-bundler/">bundlers</a>. That&#8217;s why, when working on a TypeScript project, you may never encounter any direct usages of the <code>tsc</code> command. </p>



<h3 class="wp-block-heading">tsconfig.json</h3>



<p>In order to make working with TypeScript compiler easier, you should use a <code>tsconfig.json</code> file. It&#8217;s a JSON file containing all compilation settings. This is quite important, because, in opposite to C# or Java compilers,  the TypeScript&#8217;s one allows for quite extensive (and flexible) configuration. </p>



<p>When you use the <code>tsc</code> command, it looks for <code>tsconfig.json</code> file in the current directory or any of the parent directories until it finds one. You can also provide a custom <code>tsconfig.json</code> location via <code>--project</code> parameter.</p>



<p>The simplest <code>tsconfig.json</code> file you get after initializing a new TypeScript project with <code>tsc --init</code> looks as follows:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">{<br/>  &quot;compilerOptions&quot;: {<br/>    &quot;target&quot;: &quot;es2016&quot;,<br/>    &quot;module&quot;: &quot;commonjs&quot;,<br/>    &quot;forceConsistentCasingInFileNames&quot;: true,<br/>    &quot;strict&quot;: true,<br/>    &quot;skipLibCheck&quot;: true<br/>  }<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">Default tsconfig.json</span> </div> </div></div>



<p>We will not explore all the individual settings in this article. The <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html">official documentation does a great job</a>.</p>



<h3 class="wp-block-heading">TypeScript compiler &#8211; example</h3>



<p>Let&#8217;s now see how it works.</p>



<p>Having a bit more complex TypeScript file as an example:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">class Person {<br/>  private name: string;<br/>  private age: number;<br/><br/>  constructor(name: string, age: number) {<br/>    this.name = name;<br/>    this.age = age;<br/>  }<br/><br/>  public getName(): string {<br/>    return this.name;<br/>  }<br/><br/>  public getAge(): number {<br/>    return this.age;<br/>  }<br/>}<br/><br/>const person = new Person(&quot;John&quot;, 27);<br/>console.log(person.getName()); // Output: John<br/>console.log(person.getAge()); // Output: 27</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">test.ts</span> </div> </div></div>



<p>Notice the <code>.ts</code> extension. This tells the compiler that this file contains TypeScript code.</p>



<p>Having <code>tsc</code> installed globally, we can compile it by executing the following command:</p>



<pre class="wp-block-code"><code>tsc test.ts</code></pre>



<p>For the file given above, the output of this command is the following JavaScript file:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-javascript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-javascript code-embed-code">var Person = /** @class */ (function () {<br/>  function Person(name, age) {<br/>    this.name = name;<br/>    this.age = age;<br/>  }<br/>  Person.prototype.getName = function () {<br/>    return this.name;<br/>  };<br/>  Person.prototype.getAge = function () {<br/>    return this.age;<br/>  };<br/>  return Person;<br/>})();<br/>var person = new Person(&quot;John&quot;, 27);<br/>console.log(person.getName()); // Output: John<br/>console.log(person.getAge()); // Output: 27</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">test.js</span> </div> </div></div>



<p>Few things to note:</p>



<ul class="wp-block-list">
<li>there is no information about types in the <code>.js</code> file. As we discussed before, this is intentional &#8211; only pure JavaScript code can be understood by the browser</li>



<li>notice there is no <code>class</code> keyword used in the compiled JS code, even though classes were introduced in ES2015. This is one of TypeScript compiler&#8217;s features &#8211; to produce code which is supported in most of the browsers and JS engines, without having to wait for support of new JavaScript versions</li>



<li>comments are left untouched</li>
</ul>



<p>This explains how the TypeScript compiler works. It also confirms what we stated before, that TypeScript is for programmers. As soon as your code is deployed to production, the types you added in <code>.ts</code> files are absent. The way this process is built gives a lot of advantages, but it may also be a source of confusion &#8211; let&#8217;s see how exactly.</p>



<h2 class="wp-block-heading">TypeScript compilation flaws</h2>



<p>Finally, knowing how TS -&gt; JS compilation works, let&#8217;s quickly explore some of its common flaws.</p>



<h3 class="wp-block-heading">No runtime protection</h3>



<p>As you now know, TypeScript stripes out the types during compilation. It means that the information about types is not present at runtime (when our code executes). Because of that,<strong> we are not protected by TypeScript at runtime</strong>. Consequently, if an input comes from a user and the inputs themselves are not well validated, we may still get runtime type errors. Imagine that your code expects a <code>number</code>, but the user enters a <code>string</code> because of lack of proper input validation. TypeScript will not protect you here.</p>



<p>The same applies to validating API responses. Most data from HTTP APIs comes in a form of JSON. In TypeScript, we can represent such data as <code>type</code> or <code>interface</code>. Based on those expected shapes of data, we use objects of a given type and assume that given properties are present on them or not. However, APIs may change, and TypeScript will again not protect us at runtime. We still need to <a href="https://www.codejourney.net/typing-api-responses-with-zod/">resort to alternative solutions for runtime types validation</a>.</p>



<p>To be completely clear &#8211; I don&#8217;t think that no runtime protection is something TypeScript lacks. On the contrary &#8211; I love the flexibility of TypeScript which this approach gives. It&#8217;s just how the language has been designed, and we should be aware of 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;" /></p>



<h3 class="wp-block-heading">Debugging complexity</h3>



<p>When working on a TypeScript project, the code you see on production is different from the one in your IDE. Sometimes not only types are stripped out by TypeScript compiler, but as you saw earlier it may also convert some constructs to the other (like changing a <code>class</code> to a <code>function</code>). It makes debugging, especially directly on production, more complex.</p>



<p>In order to place breakpoints and actually have them hit in your TypeScript code, you need <a href="https://code.visualstudio.com/docs/typescript/typescript-debugging#_javascript-source-map-support">source maps</a>. It does the job in most cases, but adds to the complexity at the same time, not always working seamlessly.</p>



<h3 class="wp-block-heading">TypeScript is sometimes too strict</h3>



<p>If you decide to <a href="https://www.codejourney.net/is-it-worth-migrating-to-typescript/">migrate your JS project to TypeScript</a>, you will quickly get frustrated by how strict this new language can be. Especially if you are coming from JavaScript world where <a href="https://www.codejourney.net/10-most-shocking-javascript-features-for-csharp-developers/">everything is allowed</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>There are countless memes about that, but here is the one I like:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://devs.lol/meme/for-any-emergency-in-typescript-222"><img data-recalc-dims="1" loading="lazy" decoding="async" width="576" height="505" data-attachment-id="4554" data-permalink="https://www.codejourney.net/typescript-compiler-explained/typescript-any-type-meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-any-type-meme.jpg?fit=576%2C505&amp;ssl=1" data-orig-size="576,505" 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-any-type-meme" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-any-type-meme.jpg?fit=576%2C505&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-any-type-meme.jpg?fit=576%2C505&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/10/typescript-any-type-meme.jpg?resize=576%2C505&#038;ssl=1" alt="TypeScript compiler will often let you go with any type" class="wp-image-4554"/></a></figure>
</div>


<p></p>



<p>Joking apart, most things TypeScript complaints about can be configured/turned off in <code>tsconfig.json</code> file. This is actually what I like about TypeScript. It brings static typing into JavaScript world, but lets you control how strict you want it to be. So, if you get frustrated with TypeScript compiler&#8217;s complaints, remember about <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html">configuration options</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">Summary</h2>



<p>I hope that now you feel more comfortable working with TypeScript compiler <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>If you&#8217;re a .NET developer, and you enjoyed this article, I think you may also find my free guide useful:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://mailchi.mp/055b94b02391/net-full-stack-web-developer-guide" target="_blank" rel=" noreferrer noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" width="300" height="300" data-attachment-id="4950" data-permalink="https://www.codejourney.net/how-to-become-dotnet-full-stack-in-2025-300-300/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?fit=300%2C300&amp;ssl=1" data-orig-size="300,300" 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;1&quot;}" data-image-title="How-to-become-dotnet-full-stack-in-2025-300-300" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?fit=300%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?fit=300%2C300&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?resize=300%2C300&#038;ssl=1" alt="16 Steps to become .NET full stack developer in 2025 - download a free guide" class="wp-image-4950" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?w=300&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?resize=50%2C50&amp;ssl=1 50w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></figure>
</div><p>The post <a href="https://www.codejourney.net/typescript-compiler-explained/">TypeScript Compiler Explained</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/typescript-compiler-explained/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4530</post-id>	</item>
		<item>
		<title>What Is A JavaScript Bundler?</title>
		<link>https://www.codejourney.net/what-is-a-javascript-bundler/</link>
					<comments>https://www.codejourney.net/what-is-a-javascript-bundler/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sat, 02 Sep 2023 08:16:11 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4453</guid>

					<description><![CDATA[<p>If you asked me 5 years ago what a JavaScript bundler is, I&#8217;d probably tell you it&#8217;s something people fight with for hours, just to get a simple web app set up 🤪 While this might have been closer to the truth in 2018, a lot has changed in JavaScript ecosystem until today. If you&#8217;re&#8230;</p>
<p>The post <a href="https://www.codejourney.net/what-is-a-javascript-bundler/">What Is A JavaScript Bundler?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you asked me 5 years ago what a JavaScript bundler is, I&#8217;d probably tell you it&#8217;s something people fight with for hours, just to get a simple web app set up <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> While this might have been closer to the truth in 2018, a lot has changed in JavaScript ecosystem until today.</p>



<p>If you&#8217;re starting your web development journey, or maybe have already dived into it, but are not really sure what JS bundlers are and what&#8217;s their role, you&#8217;re reading a proper piece of explanation <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-4453"></span>



<h2 class="wp-block-heading">Chaos and complexity &#8211; the issues</h2>



<p>Let&#8217;s consider a very simple JavaScript app. We have just one page <code>index.html</code>. Our HTML is hydrated with <code>index.js</code> file, which adds some interactivity to it. In order to use it, we need to import <code>index.js</code> script in <code>index.html</code> file. We also decided to use an external library (Bootstrap), so we should also link the necessary CSS.</p>



<p>We are linking the <code>index.js</code> with a <code>script</code> tag in <code>head</code> section:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-markup code-embed-pre line-numbers"  data-line="2" data-start="1" data-line-offset="0"><code class="language-markup code-embed-code">&lt;head&gt;<br/>    &lt;script type=&quot;module&quot; src=&quot;index.js&quot;&gt;&lt;/script&gt;<br/>    &lt;link<br/>      href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css&quot;<br/>      rel=&quot;stylesheet&quot;<br/>      integrity=&quot;sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65&quot;<br/>      crossorigin=&quot;anonymous&quot;<br/>    /&gt;<br/>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br/>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br/>    &lt;title&gt;My WebPage&lt;/title&gt;<br/>  &lt;/head&gt;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">Linking internal scripts and external library files in HTML page</span> </div> </div></div>



<p>Of course, as we are building a web application, we won&#8217;t put all the JavaScript code in <code>index.js</code>. That&#8217;s why we created two separate files with some functionalities: <code>my-utils.js</code> and <code>navigation.js</code>. </p>



<p>For instance, the <code>my-utils.js</code> exports a few functions:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-javascript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-javascript code-embed-code">export function doSomethingNice() {<br/>  alert(&quot;Nice!&quot;);<br/>}<br/><br/>export function notUsedFunctionA() {<br/>  alert(&quot;Not used function A&quot;);<br/>}<br/><br/>export function notUsedFunctionB() {<br/>  alert(&quot;Not used function B&quot;);<br/>}<br/><br/>export function notUsedFunctionC() {<br/>  alert(&quot;Not used function C&quot;);<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">Functions exported from a JavaScript module file</span> </div> </div></div>



<p>Notice the not used functions there &#8211; we&#8217;ll get to the point of them soon.</p>



<p>Next, our <code>index.js</code> file imports what it needs and adds some interactivity to the HTML elements:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-javascript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-javascript code-embed-code">import { doSomethingNice } from &quot;./my-utils.js&quot;;<br/>import { reloadThePage } from &quot;./navigation.js&quot;;<br/><br/>document<br/>  .getElementById(&quot;reload-page-btn&quot;)<br/>  .addEventListener(&quot;click&quot;, reloadThePage);<br/><br/>document<br/>  .getElementById(&quot;say-sth-nice-btn&quot;)<br/>  .addEventListener(&quot;click&quot;, doSomethingNice);</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">index.js &#8211; adding interactivity to index.html</span> </div> </div></div>



<p>If we now open our webpage, we can see the network activity when the page is loaded:</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1131" height="330" data-attachment-id="4464" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/html-loading-javascript-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-loading-javascript-1.png?fit=1131%2C330&amp;ssl=1" data-orig-size="1131,330" 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="html-loading-javascript-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-loading-javascript-1.png?fit=1131%2C330&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-loading-javascript-1.png?fit=1131%2C330&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-loading-javascript-1.png?resize=1131%2C330&#038;ssl=1" alt="" class="wp-image-4464" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-loading-javascript-1.png?w=1131&amp;ssl=1 1131w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-loading-javascript-1.png?resize=768%2C224&amp;ssl=1 768w" sizes="auto, (max-width: 1131px) 100vw, 1131px" /></figure>



<p></p>



<p>Notice that all 3 JavaScript files are fetched separately: <code>index.js</code>, <code>my-utils.js</code> and <code>navigation.js</code>.</p>



<p>What&#8217;s more, if you check the contents of <code>my-utils.js</code>, it obviously loads the whole script, containing even the not used functions:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="558" height="300" data-attachment-id="4465" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/html-utils-fetching-content/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-utils-fetching-content.png?fit=558%2C300&amp;ssl=1" data-orig-size="558,300" 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="html-utils-fetching-content" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-utils-fetching-content.png?fit=558%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-utils-fetching-content.png?fit=558%2C300&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/html-utils-fetching-content.png?resize=558%2C300&#038;ssl=1" alt="" class="wp-image-4465"/></figure>
</div>


<p></p>



<p>I think you might already feel that this can get a little problematic <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;" /> Imagine managing this when you have hundreds of your own JavaScript files plus dozens of external libraries. Not only will your app be making hundreds of network requests to fetch every single file, but it will always fetch everything &#8211; even the stuff your page doesn&#8217;t use.</p>



<p>Here&#8217;s where a JavaScript bundler comes into the field. </p>



<p>You can find full source code of this JavaScript app <a href="https://github.com/dsibinski/codejourney/tree/main/javascript-bundlers/no-bundler-app">here</a>.</p>



<h2 class="wp-block-heading">What does a JavaScript bundler do?</h2>



<p>JavaScript bundler produces <em>bundles</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;" /> But what is a bundle? It&#8217;s basically a static file, optimized to be served to the client (in our case: a web browser). The main goal is to produce a single bundle file from multiple dependencies. In effect, the user&#8217;s browser doesn&#8217;t need to fetch so many files separately. But how is such a bundle created?</p>



<p>First, a JavaScript bundler needs to know the <em>entry point</em>. It&#8217;s a kind of root in which our &#8220;code tree&#8221; begins. In the case of our sample JavaScript application from the previous paragraph, a perfect candidate for an entry point would be the <code>index.js</code> file. Modern bundlers support multiple entry points. It can be very useful if you&#8217;re building a multipage application, so each page can have its own entry point.</p>



<p>The next step is to create a dependency graph. The JavaScript bundler is basically starting from the root (entry point) and traverses all dependencies referenced from it, as well as all of these dependencies&#8217; dependencies. Having the dependency graph, bundler knows what is exactly used by what and in which place of our app. </p>



<p>This is how you can imagine the graph of dependencies:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><a href="https://paulallies.medium.com/webpack-managing-javascript-and-css-dependencies-3b4913f49c58"><img data-recalc-dims="1" loading="lazy" decoding="async" width="786" height="344" data-attachment-id="4469" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/webpack-dependency-graph/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-dependency-graph.webp?fit=786%2C344&amp;ssl=1" data-orig-size="786,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="webpack-dependency-graph" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-dependency-graph.webp?fit=786%2C344&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-dependency-graph.webp?fit=786%2C344&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-dependency-graph.webp?resize=786%2C344&#038;ssl=1" alt="" class="wp-image-4469" style="width:858px;height:348px" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-dependency-graph.webp?w=786&amp;ssl=1 786w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-dependency-graph.webp?resize=768%2C336&amp;ssl=1 768w" sizes="auto, (max-width: 786px) 100vw, 786px" /></a></figure>
</div>


<p></p>



<p>Module bundlers like <a href="https://webpack.js.org/">webpack</a> not only know the dependencies of your entry point. These tools even check what each dependency uses. Thanks to building such a detailed dependency graph, the bundler can introduce multiple optimizations into the bundle file.</p>



<p>Finally, JavaScript bundler outputs the actual bundles. As I mentioned, bundles can be highly optimized by applying techniques like <a href="https://webpack.js.org/guides/code-splitting/">code splitting</a>, <a href="https://vitejs.dev/guide/features.html#css">CSS inlining</a>, <a href="https://parceljs.org/features/development/#hot-reloading">HMR</a> and various performance optimizations.</p>



<p>JavaScript bundler might also ensure the backwards-compatibility with older web browsers by converting some newer JavaScript constructs used in your code to their equivalents from previous JS versions.</p>



<p>What&#8217;s interesting, modern bundlers can handle not only JS files, but also CSS, HTML and even images.</p>



<h2 class="wp-block-heading">JavaScript bundler in action</h2>



<p>Currently, the most popular JavaScript bundles is (still) <a href="https://webpack.js.org/">webpack</a>. It has been the first really advanced bundler created for both the browser and NodeJS. </p>



<p>You might have heard unpleasant things about webpack and in fact, its configuration can get really <em>spaghetti</em> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92a.png" alt="🤪" class="wp-smiley" style="height: 1em; max-height: 1em;" /> There are simpler alternatives out there, but let&#8217;s start with what&#8217;s the most common tool used in web development today. </p>



<h3 class="wp-block-heading">Adding webpack to a JavaScript app</h3>



<p>Our sample app already has a <code>package.json</code> file (we used JavaScript modules), so we can install webpack with this command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
npm install --save-dev webpack webpack-cli
</pre></div>


<p>Now we should reorganize the files a bit. Let&#8217;s put all scripts in <code>src</code> folder and move <code>index.html</code> to <code>dist</code> folder. Finally, it looks like that:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="241" height="217" data-attachment-id="4475" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/webpack-app-structure/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-structure.png?fit=241%2C217&amp;ssl=1" data-orig-size="241,217" 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="webpack-app-structure" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-structure.png?fit=241%2C217&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-structure.png?fit=241%2C217&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-structure.png?resize=241%2C217&#038;ssl=1" alt="" class="wp-image-4475"/></figure>
</div>


<p></p>



<p>Using the folder named <code>dist</code> is very common. It stands for <em>distributable</em>, which means the code ready to be distributed = served to the public. This is where our bundles will be located. As the <code>index.html</code> is directly served to the public, we also place it there.</p>



<p>With such a folders structure, there&#8217;s nothing more we need to configure for webpack to work. By default, webpack looks for <code>src/index.js</code> file which we already have and outputs bundles into the <code>dist</code> folder. To use more advanced features or multiple entry points, a <a href="https://dev.to/typescripttv/6-ways-to-configure-webpack-5a33">configuration file should be added</a>.</p>



<p>In our case, let&#8217;s go with the zero-config approach. The only thing we need is to add a <code>script</code> entry to <code>package.json</code>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-javascript code-embed-pre line-numbers"  data-line="2" data-start="1" data-line-offset="0"><code class="language-javascript code-embed-code">  &quot;scripts&quot;: {<br/>    &quot;build&quot;: &quot;webpack&quot;,<br/>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br/>  },</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">package.json with webpack build script</span> </div> </div></div>



<p>Let&#8217;s now run <code>npm run build</code> and see what happens:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="483" height="154" data-attachment-id="4476" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/webpack-build-output/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-build-output.png?fit=483%2C154&amp;ssl=1" data-orig-size="483,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="webpack-build-output" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-build-output.png?fit=483%2C154&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-build-output.png?fit=483%2C154&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-build-output.png?resize=483%2C154&#038;ssl=1" alt="" class="wp-image-4476"/></figure>
</div>


<p></p>



<p>It seems that webpack created the <code>main.js</code> asset (bundle):</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="351" height="245" data-attachment-id="4477" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/webpack-main-bundle/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-main-bundle.png?fit=351%2C245&amp;ssl=1" data-orig-size="351,245" 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="webpack-main-bundle" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-main-bundle.png?fit=351%2C245&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-main-bundle.png?fit=351%2C245&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-main-bundle.png?resize=351%2C245&#038;ssl=1" alt="" class="wp-image-4477"/></figure>
</div>


<p></p>



<p>Let&#8217;s make sure that our <code>index.html</code> page links this bundle file properly:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-markup code-embed-pre line-numbers"  data-line="4" data-start="1" data-line-offset="0"><code class="language-markup code-embed-code">&lt;!DOCTYPE html&gt;<br/>&lt;html lang=&quot;en&quot;&gt;<br/>  &lt;head&gt;<br/>    &lt;script type=&quot;module&quot; src=&quot;main.js&quot;&gt;&lt;/script&gt;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">index.html &#8211; linking main.js bundle</span> </div> </div></div>



<p>Now, let&#8217;s open our <code>index.html</code> page and see how the network requests look like now:</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1138" height="283" data-attachment-id="4478" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/webpack-app-bundle-fetching-network/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-bundle-fetching-network.png?fit=1138%2C283&amp;ssl=1" data-orig-size="1138,283" 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="webpack-app-bundle-fetching-network" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-bundle-fetching-network.png?fit=1138%2C283&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-bundle-fetching-network.png?fit=1138%2C283&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-bundle-fetching-network.png?resize=1138%2C283&#038;ssl=1" alt="" class="wp-image-4478" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-bundle-fetching-network.png?w=1138&amp;ssl=1 1138w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-bundle-fetching-network.png?resize=768%2C191&amp;ssl=1 768w" sizes="auto, (max-width: 1138px) 100vw, 1138px" /></figure>



<p></p>



<p>Wow, that&#8217;s something different from what we had previously! Notice that now only 1 script, the <code>main.js</code> file, is fetched by the webpage. There were 3 before: <code>index.js</code>, <code>my-utils.js</code> and <code>navigation.js</code>. Of course, the web page works exactly as before.</p>



<p>Let us also examine the contents of the fetched <code>main.js</code> file:</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="942" height="248" data-attachment-id="4479" data-permalink="https://www.codejourney.net/what-is-a-javascript-bundler/webpack-app-main-bundle-content/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-main-bundle-content.png?fit=942%2C248&amp;ssl=1" data-orig-size="942,248" 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="webpack-app-main-bundle-content" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-main-bundle-content.png?fit=942%2C248&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-main-bundle-content.png?fit=942%2C248&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-main-bundle-content.png?resize=942%2C248&#038;ssl=1" alt="" class="wp-image-4479" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-main-bundle-content.png?w=942&amp;ssl=1 942w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/08/webpack-app-main-bundle-content.png?resize=768%2C202&amp;ssl=1 768w" sizes="auto, (max-width: 942px) 100vw, 942px" /></figure>



<p></p>



<p>Pay attention what happened here. Webpack has nicely inlined all the external code we used directly into the <code>main.js</code> bundle. What&#8217;s more, the exported, but not used functions from <code>my-utils.js</code> are not present here at all! When building the dependency graph, webpack noticed that those functions are not used, so it didn&#8217;t include them<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>This is basically how webpack and most JavaScript bundlers work. Their role is to deliver the smallest and the most optimized bundles possible. This ultimately saves a lot of bandwidth by avoiding unnecessary network requests the client browser would otherwise need to make. Cutting out the unused code makes the bundles smaller, again reducing the network usage.</p>



<p>You can find full source code of the webpack app <a href="https://github.com/dsibinski/codejourney/tree/main/javascript-bundlers/webpack-app">here</a>.</p>



<h3 class="wp-block-heading">Webpack has a lot more to offer</h3>



<p>From all the JavaScript bundlers used today, webpack is the most advanced one. It&#8217;s the most mature one as well. It offers dozens of customizations, <a href="https://webpack.js.org/concepts/#plugins">plugins</a> and <a href="https://webpack.js.org/concepts/#loaders">loaders</a>. You can also easily add <a href="https://www.codejourney.net/is-it-worth-migrating-to-typescript/">TypeScript</a> support. </p>



<p>You can do really crazy stuff with webpack <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;" /> However, if you are starting your web development journey, don&#8217;t get overwhelmed by learning it all. Just be aware that webpack can do almost everything you might need. It&#8217;s just a matter of <a href="https://stackoverflow.com/questions/tagged/webpack">searching StackOverflow</a> or asking <a href="https://github.com/features/copilot">Copilot</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>



<h3 class="wp-block-heading">Alternatives to webpack</h3>



<p>In recent years, developers created a few other amazing JavaScript bundlers. I recommend you to pay attention to them, because webpack doesn&#8217;t have to be your first choice today. Webpack is still <a href="https://create-react-app.dev/">used in CRA</a>, which is believed to be a default way of creating new React applications. This is what makes it very widely used, but you don&#8217;t need to follow this path <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 recommend checking <a href="https://parceljs.org/">Parcel</a>, <a href="https://esbuild.github.io/">esbuild</a> and <a href="https://vitejs.dev/">ViteJS</a>. These are modern bundlers created to, among others, eliminate some of webpack&#8217;s burdens. If you&#8217;re starting out and don&#8217;t want to get yourself busy with bundling configuration, I especially recommend creating your next app with Parcel.</p>



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



<p>That&#8217;s all that you need to know about JavaScript bundlers to be able to work with them and understand what&#8217;s happening when executing this magic <code>npm run build</code> script <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>If you&#8217;re a .NET developer, and you enjoyed this article, I think you may also find my free guide useful:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://mailchi.mp/055b94b02391/net-full-stack-web-developer-guide" target="_blank" rel=" noreferrer noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" width="300" height="300" data-attachment-id="4950" data-permalink="https://www.codejourney.net/how-to-become-dotnet-full-stack-in-2025-300-300/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?fit=300%2C300&amp;ssl=1" data-orig-size="300,300" 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;1&quot;}" data-image-title="How-to-become-dotnet-full-stack-in-2025-300-300" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?fit=300%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?fit=300%2C300&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?resize=300%2C300&#038;ssl=1" alt="16 Steps to become .NET full stack developer in 2025 - download a free guide" class="wp-image-4950" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?w=300&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2025/01/How-to-become-dotnet-full-stack-in-2025-300-300.jpg?resize=50%2C50&amp;ssl=1 50w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></figure>
</div>


<p></p>
<p>The post <a href="https://www.codejourney.net/what-is-a-javascript-bundler/">What Is A JavaScript Bundler?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/what-is-a-javascript-bundler/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4453</post-id>	</item>
		<item>
		<title>How (And Why?) To Wrap External Libraries?</title>
		<link>https://www.codejourney.net/how-and-why-to-wrap-external-libraries/</link>
					<comments>https://www.codejourney.net/how-and-why-to-wrap-external-libraries/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 20 Feb 2023 09:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4346</guid>

					<description><![CDATA[<p>If you use external libraries in your application, wrapping them may be very helpful. How to wrap external libraries and why it&#8217;s worth doing that? Today we&#8217;re going to dive into that, based on a TypeScript web app example 😉 Why? You probably know what a&#160;wrapper is. As its name suggests, it&#8217;s a practice of&#8230;</p>
<p>The post <a href="https://www.codejourney.net/how-and-why-to-wrap-external-libraries/">How (And Why?) To Wrap External Libraries?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you use external libraries in your application, wrapping them may be very helpful. How to wrap external libraries and why it&#8217;s worth doing that? Today we&#8217;re going to dive into that, based on a TypeScript web app example <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-4346"></span>



<h2 class="wp-block-heading">Why?</h2>



<p>You probably know what a&nbsp;<em>wrapper</em> is. As its name suggests, it&#8217;s a practice of putting another layer on a piece of something. In our case, <em>wrapping</em>&nbsp;a piece of code in another piece of code <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>But why would you do that? To make your life easier! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br>Wrapping external libraries lets you abstract your code from their implementation details. In effect, it makes your life a lot easier when you want to keep the behavior, but change the library providing it. This approach also lets you use only those features from a given external dependency that you actually need.<br>Let&#8217;s see that with an example.</p>



<h2 class="wp-block-heading">Wrapping HTTP client</h2>



<p>A very good example is HTTP client&nbsp;wrapper. HTTP calls are used in almost every web application. In order to perform them, we need to choose an HTTP client. We can either use <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a></code>, or something more sophisticated like&nbsp;<code><a href="https://axios-http.com/docs/intro">axios</a></code>.</p>



<p>However, with time, we may decide to replace it with something else. There might be many reasons for that &#8211; either the library stops to be maintained or something new and better is out there. It would be a shame if we&#8217;d now need to change the code in those thousands of places where the current library is being used. This would take a lot of time and might be error-prone. We can definitely prepare better for such 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;" /></p>



<h3 class="wp-block-heading">Create HttpClient wrapper for axios</h3>



<p>Let&#8217;s say that, for now, we will go with <code>axios</code>. Instead of <a href="https://axios-http.com/docs/example">calling it directly from our code</a>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="2,10-11" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">import { useEffect, useState } from &quot;react&quot;;<br/>import axios from &quot;axios&quot;;<br/>import { Product } from &quot;../types/product&quot;;<br/>import { DummyJsonProductsResult } from &quot;../types/dummyJsonProductsResult&quot;;<br/><br/>export const ProductsList = () =&gt; {<br/>  const [products, setProducts] = useState&lt;Product[] | null&gt;(null);<br/><br/>  useEffect(() =&gt; {<br/>    axios<br/>      .get&lt;DummyJsonProductsResult&gt;(&quot;https://dummyjson.com/products&quot;)<br/>      .then((result) =&gt; {<br/>        setProducts(result.data.products);<br/>      });<br/>  }, []);<br/> <br/> // ...<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">ProductsList.tsx &#8211; calling axios directly from component&#039;s code</span> </div> </div></div>



<p>I will create an <em>HttpClient</em> wrapper for it and use it instead.</p>



<p>First, I create <code>httpClient.ts</code> file in <code>wrappers</code> folder. I like to have such a catalog in my React projects and keep all the wrappers there.</p>



<p>I start writing all wrappers with an interface. In that case, I treat the interface as a <em>contract</em>. It should say what I need this small wrapper to do, without worrying about implementation details.</p>



<p><code>IHttpClient</code> interface initially looks as follows:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">interface IHttpClient {<br/>  get&lt;TResponse&gt;(url: string): Promise&lt;TResponse&gt;;<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; IHttpClient interface (get only)</span> </div> </div></div>



<p>That&#8217;s what we have so far. We just need to retrieve the data with <code>GET</code> method.</p>



<p>Next step is to create the actual implementation of <code>IHttpClient</code> using <code>axios</code>. This is pretty straightforward using a <code>class</code> implementing <code>IHttpClient</code> interface and taking a look at <a href="https://axios-http.com/docs/instance"><code>axios</code>&#8216;s documentation</a>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">class AxiosHttpClient implements IHttpClient {<br/>  private instance: AxiosInstance | null = null;<br/><br/>  private get axiosClient(): AxiosInstance {<br/>    return this.instance ?? this.initAxiosClient();<br/>  }<br/><br/>  private initAxiosClient() {<br/>    return axios.create();<br/>  }<br/><br/>  get&lt;TResponse&gt;(url: string): Promise&lt;TResponse&gt; {<br/>    return new Promise&lt;TResponse&gt;((resolve, reject) =&gt; {<br/>      this.axiosClient<br/>        .get&lt;TResponse, AxiosResponse&lt;TResponse&gt;&gt;(url)<br/>        .then((result) =&gt; {<br/>          resolve(result.data);<br/>        })<br/>        .catch((error: Error | AxiosError) =&gt; {<br/>          reject(error);<br/>        });<br/>    });<br/>  }<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; AxiosHttpClient implementation (get only)</span> </div> </div></div>



<p>This implementation lets us encapsulate a simple singleton inside the class.</p>



<p>The last step here is to expose the instance of our HTTP client. Remember to <strong>always export the interface type variable</strong>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const httpClient: IHttpClient = new AxiosHttpClient();</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; exporting AxiosHttpClient as IHttpClient singleton instance</span> </div> </div></div>



<p>That&#8217;s basically how we wrap external libraries in TypeScript. Easy-peasy <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">Using the wrapper</h3>



<p>I can now use our wrapper in <code>ProductsList.tsx</code> component:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="2,10-11" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">import { useEffect, useState } from &quot;react&quot;;<br/>import { httpClient } from &quot;../wrappers/httpClient&quot;; // we don&#039;t import axios here anymore<br/>import { Product } from &quot;../types/product&quot;;<br/>import { DummyJsonProductsResult } from &quot;../types/dummyJsonProductsResult&quot;;<br/><br/>export const ProductsList = () =&gt; {<br/>  const [products, setProducts] = useState&lt;Product[] | null&gt;(null);<br/><br/>  useEffect(() =&gt; {<br/>    httpClient // instead of axios, we use our wrapper in components<br/>      .get&lt;DummyJsonProductsResult&gt;(&quot;https://dummyjson.com/products&quot;)<br/>      .then((result) =&gt; {<br/>        setProducts(result.data.products);<br/>      });<br/>  }, []);<br/> <br/> // ...<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">ProductsList.tsx &#8211; using IHttpClient wrapper</span> </div> </div></div>



<p>Notice how easy that was. Since now, we only import stuff from <code>axios</code> package in <code>httpClient.ts</code> file. Only this single file is dependent on <a href="https://www.npmjs.com/package/axios"><code>axios</code> npm package</a>. None of our components (and other project files) know about <code>axios</code>. Our IDE only knows that the wrapper is an object instance fulfilling <code>IHttpClient</code> contract:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="537" height="332" data-attachment-id="4361" data-permalink="https://www.codejourney.net/how-and-why-to-wrap-external-libraries/1_usingwrapperinterface/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?fit=537%2C332&amp;ssl=1" data-orig-size="537,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="1_UsingWrapperInterface" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?fit=537%2C332&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?fit=537%2C332&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_UsingWrapperInterface.png?resize=537%2C332&#038;ssl=1" alt="Interface-implementing wrapper instance usage in Visual Studio Code" class="wp-image-4361"/></figure>
</div>


<h3 class="wp-block-heading">Extra wrapper features</h3>



<p>Apart from nicely isolating us from dependencies, wrappers have more advantages. One of them is a possibility to configure the library in a single place. In our example with <code>axios</code> &#8211; imagine that one day you want to add custom headers to each HTTP request. Having all API calls going via <code>AxiosHttpClient</code>, you can configure such things there, in a single place. That way, you follow the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a> and keep all the logic related to <code>axios</code> (or to any other external dependency) in a single place. It also comes with benefits like easy testability etc.</p>



<p>For clarity, I also added <code>post</code> support to our <code>IHttpClient</code>. You can <a href="https://github.com/dsibinski/codejourney/commit/200f31ba0c5483f3e834a5ec4cd82566887e3d98">check it here</a>.</p>



<h2 class="wp-block-heading">Replacing the wrapped library</h2>



<p>Ok, it&#8217;s time to have our solution battle-tested. We have the HTTP client nicely wrapped and exposed as an instance of <code>IHttpClient</code>. However, we came to the conclusion that <code>axios</code> is not good enough, and we want to have it replaced with <code>fetch</code>.</p>



<p>Remember that in the real web application, you would have hundreds or thousands of usages of <code>IHttpClient</code> instance. That&#8217;s where the power of wrappers comes into play <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>So how do I make sure those thousands of usages will now use <code>fetch</code> instead of <code>axios</code>? That&#8217;s actually pretty straightforward. I&#8217;ll simply add a new class &#8211; <code>FetchHttpClient</code> implementing <code>IHttpClient</code> interface:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="4,23" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">class FetchHttpClient implements IHttpClient {<br/>  get&lt;TResponse&gt;(url: string): Promise&lt;TResponse&gt; {<br/>    return new Promise&lt;TResponse&gt;((resolve, reject) =&gt; {<br/>      fetch(url)<br/>        .then((response) =&gt;<br/>          response<br/>            .json()<br/>            .then((responseJson) =&gt; {<br/>              resolve(responseJson as TResponse);<br/>            })<br/>            .catch((error: Error) =&gt; {<br/>              reject(`Response JSON parsing error: ${error}`);<br/>            })<br/>        )<br/>        .catch((error: Error) =&gt; {<br/>          reject(error);<br/>        });<br/>    });<br/>  }<br/><br/>  post&lt;TResponse&gt;(url: string, data?: object): Promise&lt;TResponse&gt; {<br/>    return new Promise&lt;TResponse&gt;((resolve, reject) =&gt; {<br/>      fetch(url, {<br/>        method: &quot;POST&quot;,<br/>        headers: {<br/>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br/>        },<br/>        body: JSON.stringify(data),<br/>      })<br/>        .then((response) =&gt;<br/>          response<br/>            .json()<br/>            .then((responseJson) =&gt; {<br/>              resolve(responseJson as TResponse);<br/>            })<br/>            .catch((error: Error) =&gt; {<br/>              reject(`Response JSON parsing error: ${error}`);<br/>            })<br/>        )<br/>        .catch((error: Error) =&gt; {<br/>          reject(error);<br/>        });<br/>    });<br/>  }<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; new FetchHttpClient using fetch for get and post</span> </div> </div></div>



<p>For completion, I included <code>POST</code> here as well.</p>



<p>The one last thing I have to do to make our new <code>FetchHttpClient</code> be used in the whole app in place of <code>AxiosHttpClient</code> is to change a single line with export:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export const httpClient: IHttpClient = new FetchHttpClient(); // instead of new AxiosHttpClient()</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">httpClient.ts &#8211; AxiosHttpClient replaced with FetchHttpClient</span> </div> </div></div>



<p>and that&#8217;s it! Our whole application now uses <code>fetch</code> for <code>GET</code> and <code>POST</code> HTTP requests <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 even still works <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



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



<p>I hope that now you see how important it is to wrap external libraries. We have seen that on JavaScript/TypeScript app example, but this is applicable to any programming language and framework. </p>



<p>It&#8217;s always good to be as independent as possible of 3rd party stuff. Too many times I&#8217;ve been in a situation that some <code>npm</code> package is so extensively used in a project, directly in the source code in hundreds of places, that it cannot be replaced without spending several days on it. Creating wrappers forces us to think abstract, which is another great advantage.</p>



<p>You can find the complete source code here: <a href="https://github.com/dsibinski/codejourney/tree/main/wrapping-external-libraries">https://github.com/dsibinski/codejourney/tree/main/wrapping-external-libraries</a></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.10.9 - 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="1767783889" /><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>The post <a href="https://www.codejourney.net/how-and-why-to-wrap-external-libraries/">How (And Why?) To Wrap External Libraries?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/how-and-why-to-wrap-external-libraries/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4346</post-id>	</item>
		<item>
		<title>Adding Meatballs Menu To React-Table Rows</title>
		<link>https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/</link>
					<comments>https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 06 Feb 2023 08:16:17 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[bootstrap]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[react]]></category>
		<category><![CDATA[react-table]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4302</guid>

					<description><![CDATA[<p>Meatballs menu (⋯), also called three horizontal dots menu, is a great way of providing contextual options for grid rows. In this article, I will show you how to add the meatballs menu to a table built with @tanstack/react-table. After reading this article, you will know how to add such a menu to your React&#8230;</p>
<p>The post <a href="https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/">Adding Meatballs Menu To React-Table Rows</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Meatballs menu (⋯), also called <em>three horizontal dots menu</em>, is a great way of providing contextual options for grid rows. In this article, I will show you how to add the meatballs menu to a table built with <a href="https://www.npmjs.com/package/@tanstack/react-table">@tanstack/react-table</a>.</p>



<p>After reading this article, you will know how to add such a menu to your React app. The end result will look as in the highlighted picture of this article <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-4302"></span>



<h2 class="wp-block-heading">Creating a table with row selection support</h2>



<p>First, let&#8217;s define a type of data that we want to display. For our example, we will display a list of <code>Car</code>s:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">export type Car = {<br/>  id: string;<br/>  brand: string;<br/>  model: string;<br/>  productionYear: number;<br/>  isAvailable: boolean;<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">Car.ts</span> </div> </div></div>



<p>Next, we create a new component called <code>CarsTable</code>, responsible for rendering the table. We will use <a href="https://www.npmjs.com/package/@tanstack/react-table">@tanstack/react-table</a> for the table behavior and <a href="https://www.npmjs.com/package/react-bootstrap">react-bootstrap</a> for UI elements.</p>



<p>I implemented the <code>CarsTable</code> component in <a href="https://tanstack.com/table/v8/docs/examples/react/basic">quite a standard way according to react-table docs</a>, so I won&#8217;t copy-paste it here. You can check the whole component&#8217;s code <a href="https://github.com/dsibinski/react-table-context-menu/blob/faccde72b4be060c9dbca3d59d7b1506bc9f9b01/src/components/CarsTable.tsx">here</a>. What&#8217;s interesting is that I added support for row selection in a way that makes our table a <a href="https://reactjs.org/docs/forms.html#controlled-components">controlled React component</a>:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="2-3,10,14,16" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">type CarsTableProps = {<br/>  selectedCar: Car | null;<br/>  onCarSelected: (car: Car) =&gt; void;<br/>};<br/>export const CarsTable = (props: CarsTableProps) =&gt; {<br/>  return (<br/>    // ...<br/>    &lt;tbody&gt;<br/>        {table.getRowModel().rows.map((row) =&gt; {<br/>          const isActive = row.original.id === props.selectedCar?.id;<br/>          return (<br/>            &lt;tr<br/>              key={row.id}<br/>              style={isActive === true ? { backgroundColor: &quot;#3a7a11&quot; } : undefined}<br/>              onClick={() =&gt; {<br/>                props.onCarSelected(row.original);<br/>              }}<br/>            &gt;<br/>              {row.getVisibleCells().map((cell) =&gt; (<br/>                &lt;td key={cell.id}&gt;<br/>                  {flexRender(cell.column.columnDef.cell, cell.getContext())}<br/>                &lt;/td&gt;<br/>              ))}<br/>            &lt;/tr&gt;<br/>          );<br/>        })}<br/>      &lt;/tbody&gt;<br/>    // ...<br/>  )<br/>}</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">CarsTable.tsx &#8211; controlled row selection</span> </div> </div></div>



<p>As you can see, <code>selectedCar</code> and <code>onCarSelected</code> are managed from outside. Line 14 shows how the row color gets changed for the currently selected car. I recently had to deal with such a case in one of my projects.</p>



<p>So far, so good. This is how it looks, populated with sample data:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="991" height="440" data-attachment-id="4312" data-permalink="https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/1_initialtable/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_InitialTable.png?fit=991%2C440&amp;ssl=1" data-orig-size="991,440" 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_InitialTable" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_InitialTable.png?fit=991%2C440&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_InitialTable.png?fit=991%2C440&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_InitialTable.png?resize=991%2C440&#038;ssl=1" alt="react-table table with row selection support" class="wp-image-4312" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_InitialTable.png?w=991&amp;ssl=1 991w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/1_InitialTable.png?resize=768%2C341&amp;ssl=1 768w" sizes="auto, (max-width: 991px) 100vw, 991px" /></figure>
</div>


<h2 class="wp-block-heading">Adding meatballs menu</h2>



<p>Ok, we have a table. Now we want to add the meatballs menu. We need a three dots icon and a dropdown menu to open on clicking it.</p>



<p>After quickly <a href="https://react-bootstrap.github.io/components/dropdowns/">going through the react-bootstrap docs</a>, let&#8217;s create a new component for that:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">import { Dropdown } from &quot;react-bootstrap&quot;;<br/>import { Car } from &quot;../types/Car&quot;;<br/>import CustomDivToggle from &quot;./CustomDivToggle&quot;;<br/>import { BsThreeDots } from &quot;react-icons/bs&quot;;<br/><br/>export const CarRowContextMenu = ({ carRow }: { carRow: Car }) =&gt; {<br/>  return (<br/>    &lt;Dropdown key={carRow.id}&gt;<br/>      &lt;Dropdown.Toggle as={CustomDivToggle} style={{ cursor: &quot;pointer&quot; }}&gt;<br/>        &lt;BsThreeDots /&gt;<br/>      &lt;/Dropdown.Toggle&gt;<br/>      &lt;Dropdown.Menu&gt;<br/>        &lt;Dropdown.Item&gt;Option 1&lt;/Dropdown.Item&gt;<br/>        &lt;Dropdown.Item&gt;Option 2&lt;/Dropdown.Item&gt;<br/>      &lt;/Dropdown.Menu&gt;<br/>    &lt;/Dropdown&gt;<br/>  );<br/>};</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">CarRowContextMenu.tsx</span> </div> </div></div>



<p>As we want our dropdown toggle to have custom style, I had to provide <code>CustomDivToggle</code> as a <a href="https://react-bootstrap.github.io/components/dropdowns/#custom-dropdown-components">custom dropdown component</a>. It&#8217;s nothing very interesting, but you can check its implementation <a href="https://github.com/dsibinski/react-table-context-menu/blob/c98687413a28eecfc5fa4175a4b55a79dee8300f/src/components/CustomDivToggle.tsx">here</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>Next, as we&#8217;d like our meatballs menu to be an additional column in the grid, it seems natural to <a href="https://tanstack.com/table/v8/docs/guide/column-defs#column-def-types">use <code>react-table</code>&#8216;s display column</a>. Let&#8217;s try adding it:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">columnHelper.display({<br/>      id: &quot;context-menu&quot;,<br/>      cell: (cellContext) =&gt; {<br/>        const row = cellContext.row.original;<br/>        return &lt;CarRowContextMenu carRow={row} /&gt;;<br/>      },<br/>    }),</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">CarsTable.tsx &#8211; adding meatballs menu with display-type column</span> </div> </div></div>



<p>It looks we have it:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="984" height="442" data-attachment-id="4316" data-permalink="https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/3_contextmenuaddedv1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/3_ContextMenuAddedV1.png?fit=984%2C442&amp;ssl=1" data-orig-size="984,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="3_ContextMenuAddedV1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/3_ContextMenuAddedV1.png?fit=984%2C442&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/3_ContextMenuAddedV1.png?fit=984%2C442&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/3_ContextMenuAddedV1.png?resize=984%2C442&#038;ssl=1" alt="Meatballs menu added to the table with react-tabe's display column" class="wp-image-4316" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/3_ContextMenuAddedV1.png?w=984&amp;ssl=1 984w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/3_ContextMenuAddedV1.png?resize=768%2C345&amp;ssl=1 768w" sizes="auto, (max-width: 984px) 100vw, 984px" /></figure>
</div>


<p>However, after clicking through it for a while, it seems we have an issue. The toggle only opens on every 2nd click:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1140" height="498" data-attachment-id="4317" data-permalink="https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/4_contextmenudoubleclickissue/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/4_ContextMenuDoubleClickIssue.gif?fit=1153%2C504&amp;ssl=1" data-orig-size="1153,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="4_ContextMenuDoubleClickIssue" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/4_ContextMenuDoubleClickIssue.gif?fit=1153%2C504&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/4_ContextMenuDoubleClickIssue.gif?fit=1153%2C504&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/4_ContextMenuDoubleClickIssue.gif?resize=1140%2C498&#038;ssl=1" alt="Meatballs menu with react-table's display column. Double-click issue" class="wp-image-4317" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/4_ContextMenuDoubleClickIssue.gif?w=1153&amp;ssl=1 1153w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/4_ContextMenuDoubleClickIssue.gif?resize=768%2C336&amp;ssl=1 768w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>
</div>


<p>Why is that? The reason is our controlled <code>CarsTable</code> component. On clicking a new row, the change event occurs, which triggers the re-render of the <code>CarsTable</code> component (because <code>selectedCar</code> <em>actually</em> changes). It makes <code>react-table</code> re-render the table, with the meatballs menu in its default state (collapsed). On clicking the menu in the same row again, the change event occurs, but the <code>selectedCar</code> <em>does not actually change</em>, which <em>does not</em> trigger the re-render. Initially, it took me a while to figure that out <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;" /></p>



<h2 class="wp-block-heading">Fixing double-click issue</h2>



<p>In our case, a fix for the double click issue is quite simple. Instead of adding the column with the menu using <code>columnHelper.display()</code> function from <code>react-table</code>, we can render it <em>manually</em>. To do that, we should simply add a new <code>&lt;td&gt;</code> to each row of the table:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="17-19" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">&lt;tbody&gt;<br/>        {table.getRowModel().rows.map((row) =&gt; {<br/>          const isActive = row.original.id === props.selectedCar?.id;<br/>          return (<br/>            &lt;tr<br/>              key={row.id}<br/>              style={isActive === true ? { backgroundColor: &quot;#3a7a11&quot; } : undefined}<br/>              onClick={() =&gt; {<br/>                props.onCarSelected(row.original);<br/>              }}<br/>            &gt;<br/>              {row.getVisibleCells().map((cell) =&gt; (<br/>                &lt;td key={cell.id}&gt;<br/>                  {flexRender(cell.column.columnDef.cell, cell.getContext())}<br/>                &lt;/td&gt;<br/>              ))}<br/>              &lt;td&gt;<br/>                &lt;CarRowContextMenu carRow={row.original} /&gt;<br/>              &lt;/td&gt;<br/>            &lt;/tr&gt;<br/>          );<br/>        })}<br/>&lt;/tbody&gt;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">CarsTable.tsx &#8211; context menu added as a separate &lt;td&gt;</span> </div> </div></div>



<p>Additionally, to make it work, we need an additional table&#8217;s header placeholder:</p>


<div class="wp-block-wab-pastacode">
	<div class="code-embed-wrapper"> <pre class="language-typescript code-embed-pre line-numbers"  data-line="14-15" data-start="1" data-line-offset="0"><code class="language-typescript code-embed-code">&lt;thead&gt;<br/>        {table.getHeaderGroups().map((headerGroup) =&gt; (<br/>          &lt;tr key={headerGroup.id}&gt;<br/>            {headerGroup.headers.map((header) =&gt; (<br/>              &lt;th key={header.id}&gt;<br/>                {header.isPlaceholder<br/>                  ? null<br/>                  : flexRender(<br/>                      header.column.columnDef.header,<br/>                      header.getContext()<br/>                    )}<br/>              &lt;/th&gt;<br/>            ))}<br/>            {/* placeholder header for context menu */}<br/>            &lt;th&gt;&lt;/th&gt;<br/>          &lt;/tr&gt;<br/>        ))}<br/>&lt;/thead&gt;</code></pre> <div class="code-embed-infos"> <span class="code-embed-name">CarsTable.tsx &#8211; placeholder &lt;th&gt; for context menu</span> </div> </div></div>



<p>That&#8217;s it! Our `react-table` table with row selection support and the meatballs menu works like a charm now:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1140" height="493" data-attachment-id="4322" data-permalink="https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/5_contextmenufinalversion-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/5_ContextMenuFinalVersion-1.gif?fit=1150%2C497&amp;ssl=1" data-orig-size="1150,497" 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_ContextMenuFinalVersion-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/5_ContextMenuFinalVersion-1.gif?fit=1150%2C497&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/5_ContextMenuFinalVersion-1.gif?fit=1150%2C497&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/5_ContextMenuFinalVersion-1.gif?resize=1140%2C493&#038;ssl=1" alt="react-table table with row selection and meatballs menu - final version" class="wp-image-4322" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/5_ContextMenuFinalVersion-1.gif?w=1150&amp;ssl=1 1150w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/02/5_ContextMenuFinalVersion-1.gif?resize=768%2C332&amp;ssl=1 768w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>
</div>


<h2 class="wp-block-heading">Meatballs menu with react-table &#8211; source code</h2>



<p>You can find the complete <a href="https://github.com/dsibinski/react-table-context-menu">source code here</a>. I hope you find it useful! <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>


<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.10.9 - 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="1767783889" /><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>The post <a href="https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/">Adding Meatballs Menu To React-Table Rows</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/adding-meatballs-menu-to-react-table-rows/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4302</post-id>	</item>
		<item>
		<title>10 VS Code Extensions I Couldn&#8217;t Live Without</title>
		<link>https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/</link>
					<comments>https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 19 Jan 2023 18:57:07 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[react]]></category>
		<category><![CDATA[road-to-dotnet-full-stack]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[vscode]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4232</guid>

					<description><![CDATA[<p>I love VS Code 😍 There&#8217;s no better web code editor out there for me. Today, I&#8217;m going to share with you the 10 VS Code extensions that make my life easier. I can&#8217;t imagine coding without them. Let&#8217;s dive into it! Prettier My number one. I was a bit skeptical initially, but today I&#8230;</p>
<p>The post <a href="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/">10 VS Code Extensions I Couldn&#8217;t Live Without</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I love VS Code <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60d.png" alt="😍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> There&#8217;s no better web code editor out there for me. Today, I&#8217;m going to share with you the 10 VS Code extensions that make my life easier. I can&#8217;t imagine coding without them. Let&#8217;s dive into it!</p>



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



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">Prettier</a></h2>



<p>My number one. I was a bit skeptical initially, but today I can&#8217;t imagine my life without Prettier <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;" /> For those unfamiliar with the tool, Prettier is an <em>opinionated</em> code formatted. Opinionated, because it allows for almost no configuration. It reformats your code automatically based on its own rules.</p>



<p>It may sound scary and limiting, but it really frees your mind. Suddenly you forget about all those <em>spaces vs tabs wars</em> and discussions on which column shall the code be wrapped. Prettier does that all automatically. It can even be done on saving the file! Just take a look, how beautiful that is:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="917" height="637" data-attachment-id="4236" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/1_vscode_prettier/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/1_VSCode_Prettier.gif?fit=917%2C637&amp;ssl=1" data-orig-size="917,637" 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_VSCode_Prettier" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/1_VSCode_Prettier.gif?fit=300%2C208&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/1_VSCode_Prettier.gif?fit=917%2C637&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/1_VSCode_Prettier.gif?resize=917%2C637&#038;ssl=1" alt="Gif presenting Prettier auto-formatting on saving the file in VS Code" class="wp-image-4236"/></figure>
</div>


<p></p>



<p>It is also very easy to <a href="https://prettier.io/docs/en/precommit.html">execute prettier formatting with pre-commit git hook</a>, so the checked-in code is always formatted, even if some team members don&#8217;t use it in their IDE.</p>



<p>Never again without Prettier! <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"><a href="https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets">ES7+ React/Redux/React-Native snippets</a></h2>



<p>This is one of the first VS Code extensions I installed. It&#8217;s simple, yet very powerful! This plugin adds multiple JavaScript/React snippets. I create many new components every day. Snippets make it very easy:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="932" height="487" data-attachment-id="4239" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/2_vscode_react_snippets/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/2_VSCode_React_snippets.gif?fit=932%2C487&amp;ssl=1" data-orig-size="932,487" 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_VSCode_React_snippets" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/2_VSCode_React_snippets.gif?fit=300%2C157&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/2_VSCode_React_snippets.gif?fit=932%2C487&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/2_VSCode_React_snippets.gif?resize=932%2C487&#038;ssl=1" alt="One of the VS Code extensions that adds React snipets" class="wp-image-4239"/></figure>
</div>


<p></p>



<p>I recommend trying this extension out and exploring its built-in snippets.</p>



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=adrianwilczynski.csharp-to-typescript">C# to TypeScript</a></h2>



<p>This one is a time-saver for .NET developers working with TypeScript. It allows generating TypeScript interfaces from C# classes. You can simply copy a C# <code>class</code> and paste is as a TypeScript&#8217;s <code>interface</code> in Visual Studio Code:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1005" height="431" data-attachment-id="4241" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/3_vscode_csharp_to_typescript-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/3_VSCode_CSharp_to_TypeScript-1.gif?fit=1005%2C431&amp;ssl=1" data-orig-size="1005,431" 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_VSCode_CSharp_to_TypeScript-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/3_VSCode_CSharp_to_TypeScript-1.gif?fit=300%2C129&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/3_VSCode_CSharp_to_TypeScript-1.gif?fit=1005%2C431&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/3_VSCode_CSharp_to_TypeScript-1.gif?resize=1005%2C431&#038;ssl=1" alt="" class="wp-image-4241"/></figure>
</div>


<p></p>



<p>You can also paste using keyboard shortcuts. There&#8217;s even <a href="https://www.nuget.org/packages/CSharpToTypeScript.CLITool/">a CLI tool</a> available in case you&#8217;d want to automate this process. This extension doesn&#8217;t support all scenarios (especially no support for <code>records</code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f62d.png" alt="😭" class="wp-smiley" style="height: 1em; max-height: 1em;" />), but it still covers most simple copy-paste cases. By the way, synchronizing C# with TypeScript types is one of the challenges for full stack .NET developers.</p>



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=mattpocock.ts-error-translator">Total TypeScript</a></h2>



<p>From all VS Code extensions I use, this is the only one that actually helps me learn on the job. It was called <em>TypeScript Error Translator</em> before, and this is what I initially used it for. It basically provides more meaningful, crowdsourced translations for often enigmatic TypeScript errors:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="821" height="280" data-attachment-id="4243" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/4_vscode_errorstranslator/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?fit=821%2C280&amp;ssl=1" data-orig-size="821,280" 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_VSCode_ErrorsTranslator" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?fit=300%2C102&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?fit=821%2C280&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?resize=821%2C280&#038;ssl=1" alt="TypeScript error translator shows nice explanation of TS error" class="wp-image-4243" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?w=821&amp;ssl=1 821w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?resize=300%2C102&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/4_VSCode_ErrorsTranslator.png?resize=768%2C262&amp;ssl=1 768w" sizes="auto, (max-width: 821px) 100vw, 821px" /></figure>
</div>


<p></p>



<p>When a translation is missing, you can always contribute one. Additionally, as its new name suggests, it also lets you learn programming concepts directly inside your code. As soon as it finds a new concept in the code, a brief explanation is shown:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="485" data-attachment-id="4244" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/5_vscode_totaltypescriptlearning/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?fit=2082%2C986&amp;ssl=1" data-orig-size="2082,986" 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_VSCode_TotalTypescriptLearning" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?fit=300%2C142&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?fit=1024%2C485&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?resize=1024%2C485&#038;ssl=1" alt="" class="wp-image-4244" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?resize=1024%2C485&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?resize=300%2C142&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?resize=768%2C364&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?resize=1536%2C727&amp;ssl=1 1536w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/5_VSCode_TotalTypescriptLearning.png?resize=2048%2C970&amp;ssl=1 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p></p>



<p>It will stop highlighting this particular type of concept as soon as you mark it as learned. I think it&#8217;s a quite interesting way of learning on the job <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">ESLint</a></h2>



<p>This is the extension for integrating the most well-known linter for JavaScript into Visual Studio Code. <a href="https://eslint.org/">ESLint</a> is a static analyzer of your source code which helps you find problems quickly. It will highlight issues in your code for all loaded files from your workspace. I don&#8217;t feel there&#8217;s much to write about here &#8211; just <a href="https://eslint.org/">check their website</a> and give this extension 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;" /></p>



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client">Thunder Client</a></h2>



<p>Thunder Client is like <a href="https://www.postman.com/">Postman</a>, but built into VS Code. It lets you easily play with HTTP APIs. You can create your own collections of requests and export them to JSON, which can be checked into the source control.</p>



<p>Yet another very useful extension! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f44d.png" alt="👍" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=zenclabs.previewjs">Preview.js</a></h2>



<p>This is one of my recent discoveries. Preview.js allows to live-preview React, Solid or Vue components directly in VS Code. It also generates the initial props data, sometimes even for complex objects:</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1140" height="593" data-attachment-id="4261" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/6_vscode_previewjs-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/6_VSCode_PreviewJS-2.gif?fit=1467%2C763&amp;ssl=1" data-orig-size="1467,763" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="6_VSCode_PreviewJS-2" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/6_VSCode_PreviewJS-2.gif?fit=1467%2C763&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/6_VSCode_PreviewJS-2.gif?fit=1467%2C763&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/6_VSCode_PreviewJS-2.gif?resize=1140%2C593&#038;ssl=1" alt="" class="wp-image-4261" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/6_VSCode_PreviewJS-2.gif?w=1467&amp;ssl=1 1467w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/6_VSCode_PreviewJS-2.gif?resize=768%2C399&amp;ssl=1 768w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p></p>



<p>The plugin is also configurable for custom scenarios like external dependencies. You can find more information <a href="https://previewjs.com/docs/config">in the documentation</a>.</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.10.9 - 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="1767783889" /><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 -->



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=WakaTime.vscode-wakatime">WakaTime</a></h2>



<p>If you like analytics, you should check this VS Code extension. WakaTime measures how much time you spend actually writing code. It shows exactly in which language you programmed for how much time. It also divides time entries into projects you worked on:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1140" height="1018" data-attachment-id="4264" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/7_wakatime_samplestats/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?fit=2062%2C1842&amp;ssl=1" data-orig-size="2062,1842" 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_WakaTime_SampleStats" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?fit=2062%2C1842&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?fit=2062%2C1842&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?resize=1140%2C1018&#038;ssl=1" alt="" class="wp-image-4264" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?w=2062&amp;ssl=1 2062w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?resize=768%2C686&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?resize=1536%2C1372&amp;ssl=1 1536w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/7_WakaTime_SampleStats.png?resize=2048%2C1829&amp;ssl=1 2048w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>
</div>


<p></p>



<p>It&#8217;s interesting to get such insights &#8220;for free&#8221; and see how little time we spend <em>actually</em> coding <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;" />Try it for yourself and let me know your results!</p>



<h2 class="wp-block-heading"><a href="https://marketplace.visualstudio.com/items?itemName=zhuangtongfa.Material-theme">One Dark Pro</a></h2>



<p>Who never started a new project by installing fancy tools, text editors or choosing the best color theme for your IDE? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f604.png" alt="😄" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Of course &#8211; good colors = smooth -and pleasant &#8211; coding <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;" /> One Dark Pro is a must-have theme for my Visual Studio Code. I love it, it makes source code much more readable for me. What&#8217;s your favorite color theme for VS Code? <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"><a href="https://marketplace.visualstudio.com/items?itemName=vscode-icons-team.vscode-icons">vscode-icons</a></h2>



<p>Last but not least, a good friend to the One Dard Pro theme, legendary VS Code icons set. It has over 13M installs! <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;" /></p>



<p>Apart from getting +100 to fanciness <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;" />, it makes icons more explicit in the explorer:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="599" height="612" data-attachment-id="4265" data-permalink="https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/8_vscodeicons/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/8_VSCodeIcons.png?fit=599%2C612&amp;ssl=1" data-orig-size="599,612" 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_VSCodeIcons" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/8_VSCodeIcons.png?fit=599%2C612&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/8_VSCodeIcons.png?fit=599%2C612&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/8_VSCodeIcons.png?resize=599%2C612&#038;ssl=1" alt="" class="wp-image-4265" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/8_VSCodeIcons.png?w=599&amp;ssl=1 599w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2023/01/8_VSCodeIcons.png?resize=50%2C50&amp;ssl=1 50w" sizes="auto, (max-width: 599px) 100vw, 599px" /></figure>
</div>


<p></p>



<p>As you can see, it even guesses the folder type based on its name &#8211; see <code>types</code> or <code>utils</code> folders&#8217; icons above.</p>



<p>Not critical, yet helpful. Undeniably adds a million to your professionalism as a web developer <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;" /><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;" /><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">Summary</h2>



<p>So, that&#8217;s it! The list of my 10 favorite Visual Studio Code extensions. </p>



<p>What about you? What are your must-have VS Code extensions? <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/10-vs-code-extensions-i-couldnt-live-without/">10 VS Code Extensions I Couldn&#8217;t Live Without</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/10-vs-code-extensions-i-couldnt-live-without/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4232</post-id>	</item>
		<item>
		<title>How To Fix Visual Studio Code IntelliSense Loading Infinitely</title>
		<link>https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/</link>
					<comments>https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 09 Oct 2022 08:57:31 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[intellisense]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[typescript]]></category>
		<category><![CDATA[visual studio code]]></category>
		<category><![CDATA[vscode]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=4188</guid>

					<description><![CDATA[<p>Continuing with weird errors you might encounter in JavaScript world, I have another one: Visual Studio Code IntelliSense loading infinitely 😀 Solution included, of course! The symptoms of this issue are putting your mouse on something where you&#8217;d expect the IntelliSense guidelines, but instead you only see the &#8220;Loading&#8230;&#8221; text. In this short article, I&#8217;m&#8230;</p>
<p>The post <a href="https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/">How To Fix Visual Studio Code IntelliSense Loading Infinitely</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Continuing with <a href="https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/">weird errors you might encounter in JavaScript world</a>, I have another one: <strong>Visual Studio Code IntelliSense loading infinitely</strong> <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;" /> Solution included, of course!</p>



<p>The symptoms of this issue are putting your mouse on something where you&#8217;d expect the IntelliSense guidelines, but instead you only see the &#8220;Loading&#8230;&#8221; text.</p>



<p>In this short article, I&#8217;m sharing the reason of this issue and my way of fixing it.</p>



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



<h2 class="wp-block-heading">How VS Code Infinite IntelliSense Loading Looks Like</h2>



<p>This is what I struggled with:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="4195" data-permalink="https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/2_vscodeloadingissue/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/2_VSCodeLoadingIssue.gif?fit=497%2C907&amp;ssl=1" data-orig-size="497,907" 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_VSCodeLoadingIssue" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/2_VSCodeLoadingIssue.gif?fit=164%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/2_VSCodeLoadingIssue.gif?fit=497%2C907&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/2_VSCodeLoadingIssue.gif?resize=497%2C907&#038;ssl=1" alt="Visual Studio Code IntelliSense Loading Infinitely - a gif animation" class="wp-image-4195" style="width:497px;height:907px" width="497" height="907"/></figure>
</div>


<p>As you can see, I didn&#8217;t get any IntelliSense while hovering my mouse on various elements in the editor.</p>



<p>A similar thing happened when I tried to use <code>Go to References</code> (or <code>Shift</code> + <code>F12</code> on Windows) for any object:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="509" height="907" data-attachment-id="4197" data-permalink="https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/3_vscode_find_references_loading/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/3_VSCode_find_references_loading.gif?fit=509%2C907&amp;ssl=1" data-orig-size="509,907" 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_VSCode_find_references_loading" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/3_VSCode_find_references_loading.gif?fit=168%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/3_VSCode_find_references_loading.gif?fit=509%2C907&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/3_VSCode_find_references_loading.gif?resize=509%2C907&#038;ssl=1" alt="Visual Studio Code IntelliSense Loading Infinitely for Go to References - a gif animation" class="wp-image-4197"/></figure>
</div>


<p>As you can see, the loading bar at the top of VS Code was showing progress infinitely.</p>



<p>Let&#8217;s now see how to fix this annoying issue <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">Fixing Visual Studio Code IntelliSense Loading Infinitely</h2>



<p>After quite long investigation, I finally found the reason. It turned out that <strong><a href="https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions">sometimes your Visual Studio Code might be using a different TypeScript version than your workspace uses</a></strong>. In my case, it was exactly the cause of the infinite loading problem <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d0.png" alt="🧐" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>In order to fix it, use <code>TypeScript: Select TypeScript Version...</code> command. You can access commands with <code>Ctrl + Shift + P</code> on Windows or <code>⇧⌘P</code> on Mac:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="600" height="262" data-attachment-id="4199" data-permalink="https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/5_selecttypescriptversion/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/5_SelectTypeScriptVersion.png?fit=600%2C262&amp;ssl=1" data-orig-size="600,262" 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_SelectTypeScriptVersion" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/5_SelectTypeScriptVersion.png?fit=300%2C131&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/5_SelectTypeScriptVersion.png?fit=600%2C262&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/5_SelectTypeScriptVersion.png?resize=600%2C262&#038;ssl=1" alt="Visual Studio Code: command palette view, &quot;TypeScript: Select TypeScript Version&quot; command" class="wp-image-4199" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/5_SelectTypeScriptVersion.png?w=600&amp;ssl=1 600w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/5_SelectTypeScriptVersion.png?resize=300%2C131&amp;ssl=1 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure>
</div>


<p>Select this command and tell Visual Studio Code to use the workspace version of TypeScript:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="627" height="139" data-attachment-id="4200" data-permalink="https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/6_selecttypescriptversion_useworkspaceversion/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/6_SelectTypeScriptVersion_UseWorkspaceVersion.png?fit=627%2C139&amp;ssl=1" data-orig-size="627,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="6_SelectTypeScriptVersion_UseWorkspaceVersion" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/6_SelectTypeScriptVersion_UseWorkspaceVersion.png?fit=300%2C67&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/6_SelectTypeScriptVersion_UseWorkspaceVersion.png?fit=627%2C139&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/6_SelectTypeScriptVersion_UseWorkspaceVersion.png?resize=627%2C139&#038;ssl=1" alt="Visual Studio Code: command palette view, &quot;TypeScript: Select TypeScript Version&quot; command, telling VS Code to use workspace version of TypeScript" class="wp-image-4200" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/6_SelectTypeScriptVersion_UseWorkspaceVersion.png?w=627&amp;ssl=1 627w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/10/6_SelectTypeScriptVersion_UseWorkspaceVersion.png?resize=300%2C67&amp;ssl=1 300w" sizes="auto, (max-width: 627px) 100vw, 627px" /></figure>
</div>


<p>As you can see on the screenshot above, in my case the VS Code&#8217;s TypeScript version was <code>4.8.2</code>, while the workspace version was <code>4.8.3</code>. Changing it to use the newer, workspace version solved the problem. Visual Studio Code IntelliSense loading infinitely issue was gone <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;" /></p>



<p>If it doesn&#8217;t work straightaway, you might need restarting your VS Code editor.</p>



<p>I hope that worked for you and saved you some hours of debugging and exploring StackOverflow <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>


<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.10.9 - 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="1767783889" /><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>The post <a href="https://www.codejourney.net/how-to-fix-visual-studio-code-intellisense-loading-infinitely/">How To Fix Visual Studio Code IntelliSense Loading Infinitely</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-visual-studio-code-intellisense-loading-infinitely/feed/</wfw:commentRss>
			<slash:comments>20</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4188</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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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"><span class=pl-en>getAllUsers</span> <span class=pl-c1>=</span> <span class=pl-k>async</span> <span class=pl-kos>(</span><span class=pl-kos>)</span>: <span class=pl-smi>Promise</span><span class=pl-c1>&lt;</span><span class=pl-smi>UserViewModel</span><span class=pl-kos>[</span><span class=pl-kos>]</span><span class=pl-c1>&gt;</span> <span class=pl-c1>=&gt;</span> <span class=pl-kos>{</span></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">    <span class=pl-k>const</span> <span class=pl-s1>url</span> <span class=pl-c1>=</span> <span class=pl-s>`<span class=pl-s1><span class=pl-kos>${</span><span class=pl-smi>this</span><span class=pl-kos>.</span><span class=pl-c1>apiEndpoint</span><span class=pl-kos>}</span></span>/AllUsers`</span><span class=pl-kos>;</span></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">    <span class=pl-k>const</span> <span class=pl-s1>response</span> <span class=pl-c1>=</span> <span class=pl-k>await</span> <span class=pl-en>fetch</span><span class=pl-kos>(</span><span class=pl-s1>url</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">    <span class=pl-k>const</span> <span class=pl-s1>users</span> <span class=pl-c1>=</span> <span class=pl-kos>(</span><span class=pl-k>await</span> <span class=pl-s1>response</span><span class=pl-kos>.</span><span class=pl-en>json</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>)</span> <span class=pl-k>as</span> <span class=pl-smi>UserViewModel</span><span class=pl-kos>[</span><span class=pl-kos>]</span><span class=pl-kos>;</span></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">    <span class=pl-k>return</span> <span class=pl-s1>users</span><span class=pl-kos>;</span></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">  <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/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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

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


    </div>

  </div>
</div>

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

</div></figure>



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



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



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

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

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/1_UsersListTyped.png?fit=300%2C164&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/2_UsersDataDispayed.png?fit=300%2C120&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/3_UserdDataWithoutLoyaltyPointsDisplayed.png?fit=300%2C125&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/4_TSOutdatedUserViewModel.png?fit=300%2C171&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/5_TSOldPropertyUndefined.png?fit=300%2C142&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?fit=300%2C163&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?fit=441%2C239&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?resize=441%2C239&#038;ssl=1" alt="At runtime we can see the new fidelityPoints property already present" class="wp-image-4117" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?w=441&amp;ssl=1 441w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/6_NewPropertyPresentAtJsRuntime.png?resize=300%2C163&amp;ssl=1 300w" sizes="auto, (max-width: 441px) 100vw, 441px" /></figure>
</div>


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



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



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



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



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



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



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



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


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


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



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



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

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

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

  <table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="UserViewModel_ZodSchema.ts">
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-userviewmodel_zodschema-ts-LC1" class="blob-code blob-code-inner js-file-line"><span class=pl-k>export</span> <span class=pl-k>const</span> <span class=pl-v>UserViewModelSchema</span> <span class=pl-c1>=</span> <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>object</span><span class=pl-kos>(</span><span class=pl-kos>{</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-userviewmodel_zodschema-ts-LC2" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>id</span>: <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>string</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>.</span><span class=pl-en>uuid</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-userviewmodel_zodschema-ts-LC3" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>name</span>: <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>string</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-userviewmodel_zodschema-ts-LC4" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>lastName</span>: <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>string</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-userviewmodel_zodschema-ts-LC5" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>login</span>: <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>string</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-userviewmodel_zodschema-ts-LC6" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>isActive</span>: <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>boolean</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-userviewmodel_zodschema-ts-LC7" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>loyaltyPoints</span>: <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>number</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-userviewmodel_zodschema-ts-LC8" class="blob-code blob-code-inner js-file-line">  <span class=pl-c1>address</span>: <span class=pl-v>AddressViewModelSchema</span><span class=pl-kos>.</span><span class=pl-en>nullable</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>,</span></td>
        </tr>
        <tr>
          <td id="file-userviewmodel_zodschema-ts-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-userviewmodel_zodschema-ts-LC9" class="blob-code blob-code-inner js-file-line"><span class=pl-kos>}</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/9c7759dff996babccf1b14da276d76c8/raw/959d8bf640a1f20dc10b7975c7a8fa40e62392d5/UserViewModel_ZodSchema.ts" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/9c7759dff996babccf1b14da276d76c8#file-userviewmodel_zodschema-ts" class="Link--inTextBlock">
          UserViewModel_ZodSchema.ts
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



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



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



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



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



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



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



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

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

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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"><span class=pl-en>getAllUsers</span> <span class=pl-c1>=</span> <span class=pl-k>async</span> <span class=pl-kos>(</span><span class=pl-kos>)</span>: <span class=pl-smi>Promise</span><span class=pl-c1>&lt;</span><span class=pl-smi>UserViewModel</span><span class=pl-kos>[</span><span class=pl-kos>]</span><span class=pl-c1>&gt;</span> <span class=pl-c1>=&gt;</span> <span class=pl-kos>{</span></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">  <span class=pl-k>const</span> <span class=pl-s1>url</span> <span class=pl-c1>=</span> <span class=pl-s>`<span class=pl-s1><span class=pl-kos>${</span><span class=pl-smi>this</span><span class=pl-kos>.</span><span class=pl-c1>apiEndpoint</span><span class=pl-kos>}</span></span>/AllUsers`</span><span class=pl-kos>;</span></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">  <span class=pl-k>const</span> <span class=pl-s1>response</span> <span class=pl-c1>=</span> <span class=pl-k>await</span> <span class=pl-en>fetch</span><span class=pl-kos>(</span><span class=pl-s1>url</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">  <span class=pl-k>const</span> <span class=pl-s1>usersJson</span> <span class=pl-c1>=</span> <span class=pl-k>await</span> <span class=pl-s1>response</span><span class=pl-kos>.</span><span class=pl-en>json</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">  <span class=pl-k>const</span> <span class=pl-s1>users</span> <span class=pl-c1>=</span> <span class=pl-s1>z</span><span class=pl-kos>.</span><span class=pl-en>array</span><span class=pl-kos>(</span><span class=pl-v>UserViewModelSchema</span><span class=pl-kos>)</span><span class=pl-kos>.</span><span class=pl-en>parse</span><span class=pl-kos>(</span><span class=pl-s1>usersJson</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">  <span class=pl-k>return</span> <span class=pl-s1>users</span><span class=pl-kos>;</span></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"><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/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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/07/7_ZodSchemaValidationError.png?fit=300%2C273&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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">[TestFixture]</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">public class MyTests</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">{</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">    [Test]</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">    public void SampleTest()</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">    {</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">        // some operations here, like starting a server for tests in-memory&#8230;</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">        TestContext.Progress.WriteLine(&quot;The server is running now! You can reach it on https://localhost:8067/&quot;);</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">        while (true)</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">        {</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">            // keep it running on purpose (e.g. for E2E tests)</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">        }</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">    }</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">}</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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/06/NUnit_cmd_console_progress.png?fit=300%2C55&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_database_transient_problems.png?fit=300%2C84&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_serverless.png?fit=300%2C112&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2022/05/Azure_tier_settings_basic.png?fit=300%2C148&amp;ssl=1" 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>How to fix: npm ERR! enoent ENOENT: no such file or directory, rename</title>
		<link>https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/</link>
					<comments>https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Fri, 30 Apr 2021 04:33:47 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[npm ERR! enoent ENOENT]]></category>
		<category><![CDATA[npm error]]></category>
		<category><![CDATA[npm install package]]></category>
		<category><![CDATA[react]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3927</guid>

					<description><![CDATA[<p>I recently struggled for a while with an npm error thrown when executing npm install of some package. The error message was npm ERR! enoent ENOENT: no such file or directory, rename 'D:\\WebApp\\node_modules\\lz-string' -&#62; 'D:\\WebApp\\node_modules.lz-string.DELETE' Finally, I found a solution and a reason for that issue. The error occurred when I was trying to install&#8230;</p>
<p>The post <a href="https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/">How to fix: npm ERR! enoent ENOENT: no such file or directory, rename</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p>I recently struggled for a while with an <code>npm</code> error thrown when executing <code>npm install</code> of some package. The error message was <code>npm ERR! enoent ENOENT: no such file or directory, rename 'D:\\WebApp\\node_modules\\lz-string' -&gt; 'D:\\WebApp\\node_modules.lz-string.DELETE'</code></p>



<p>Finally, I found a solution and a reason for that issue.</p>



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



<p>The error occurred when I was trying to install <code>@testing-library/react</code> npm package. It looked like that:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1024" height="404" data-attachment-id="3928" data-permalink="https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/npm_rename_error/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?fit=1360%2C536&amp;ssl=1" data-orig-size="1360,536" 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="npm_rename_error" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?fit=300%2C118&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?fit=1024%2C404&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?resize=1024%2C404&#038;ssl=1" alt="npm ERR! enoent ENOENT error in Visual Studio Code" class="wp-image-3928" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?resize=1024%2C404&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?resize=300%2C118&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?resize=768%2C303&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?resize=676%2C266&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/npm_rename_error.png?w=1360&amp;ssl=1 1360w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>
</div>


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



<p>If you ever get this error, the hotfix is to follow these steps:</p>



<ul class="wp-block-list"><li>delete <code>node-modules</code> folder</li><li>run command <code>npm cache clean --force</code></li><li>run command <code>npm install</code></li><li>install the package again with <code>npm install your-package-name</code></li></ul>



<p>It should all work fine after that. </p>



<p>If these commands still don&#8217;t solve your issue, and you use <code>git</code> as a source control system, you can try the unbeatable <code>git clean -fdx</code> command. After that, run <code>npm install</code> again. Beware &#8211; it removes all files not checked in to git. It may also remove your IDE settings etc., so use with care.</p>



<p>But it&#8217;s only a hotfix, a solution <em>for now</em> to unblock you.</p>



<h2 class="wp-block-heading">Coldfix (solution)</h2>



<p>The real reason for this issue in my case turned out to be related to <code>jest</code>. However, not to the testing library itself, but to <a href="https://marketplace.visualstudio.com/items?itemName=Orta.vscode-jest" target="_blank" rel="noreferrer noopener">jest extension for Visual Studio Code</a>.</p>



<p>The reason for the issue is the jest tests runner working in the background. You can see that in the VS Code bottom bar:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="320" height="158" data-attachment-id="3929" data-permalink="https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/vscode_jest_runner/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/vsCode_jest_runner.png?fit=320%2C158&amp;ssl=1" data-orig-size="320,158" 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="vsCode_jest_runner" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/vsCode_jest_runner.png?fit=300%2C148&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/vsCode_jest_runner.png?fit=320%2C158&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/vsCode_jest_runner.png?resize=320%2C158&#038;ssl=1" alt="Visual Studio Code - jest runner" class="wp-image-3929" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/vsCode_jest_runner.png?w=320&amp;ssl=1 320w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/vsCode_jest_runner.png?resize=300%2C148&amp;ssl=1 300w" sizes="auto, (max-width: 320px) 100vw, 320px" /></figure>
</div>


<p>The real solution is to disable jest runner when installing new packages. You can do it with a <code>Jest: Stop Runner</code> command in Ctrl+Shift+P:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="777" height="246" data-attachment-id="3930" data-permalink="https://www.codejourney.net/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/vscode_jest_stop_runner/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?fit=777%2C246&amp;ssl=1" data-orig-size="777,246" 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="VSCode_jest_stop_runner" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?fit=300%2C95&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?fit=777%2C246&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?resize=777%2C246&#038;ssl=1" alt="npm ERR! enoent ENOENT fix in Visual Studio by stopping jest runner" class="wp-image-3930" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?w=777&amp;ssl=1 777w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?resize=300%2C95&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?resize=768%2C243&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2021/04/VSCode_jest_stop_runner.png?resize=676%2C214&amp;ssl=1 676w" sizes="auto, (max-width: 777px) 100vw, 777px" /></figure>
</div>


<p>I don&#8217;t know exactly why this is an issue. I guess jest runner is blocking some files in <code>node-modules</code>, so they cannot be renamed/processed. I hope it helps you too <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/how-to-fix-npm-err-enoent-enoent-no-such-file-or-directory-rename/">How to fix: npm ERR! enoent ENOENT: no such file or directory, rename</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-npm-err-enoent-enoent-no-such-file-or-directory-rename/feed/</wfw:commentRss>
			<slash:comments>13</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3927</post-id>	</item>
		<item>
		<title>Improve your tests with Assert Object Pattern</title>
		<link>https://www.codejourney.net/improve-your-tests-with-assert-object-pattern/</link>
					<comments>https://www.codejourney.net/improve-your-tests-with-assert-object-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 09 Nov 2020 20:42:34 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[assert object]]></category>
		<category><![CDATA[assert object pattern]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3888</guid>

					<description><![CDATA[<p>The Asserts Hell Let&#8217;s consider the following unit test: What&#8217;s wrong here? Given and When sections are great single-liners. We know straightaway what&#8217;s the input and the action executed. However, Then block is too complex. It&#8217;s hard to figure out, just passing quickly through this test, what is expected. This case is even not that&#8230;</p>
<p>The post <a href="https://www.codejourney.net/improve-your-tests-with-assert-object-pattern/">Improve your tests with Assert Object Pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Today I&#8217;d like to share with you a very interesting concept in software testing &#8211; Assert Object pattern. It makes the <em>Assert</em> part of a test much simpler and more readable. Let&#8217;s dive right into 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>



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





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



<p>Let&#8217;s consider the following unit test:</p>



<script src="https://gist.github.com/dsibinski/f8fea58079d68dd8ac0d194a33964e1b.js"></script>



<p>What&#8217;s wrong here? <em>Given</em> and <em>When</em> sections are great single-liners. We know straightaway what&#8217;s the input and the action executed. However, <em>Then</em> block is too complex. It&#8217;s hard to figure out, just passing quickly through this test, what is <em>expected</em>. This case is even not that bad thanks to the usage of <a href="https://fluentassertions.com/">FluentAssertions</a>.</p>



<p>I spend a lot of time writing tests (<a href="https://www.codejourney.net/2017/03/unit-testing-xamarin-application/">unit</a> or integration), but I spend even more time reading them. I always hope that I will find these <em>idyllic</em> tests that act as code documentation&#8230; <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d0.png" alt="🧐" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>However, let&#8217;s go step by step. I recently took place in a <a href="https://smarttesting.pl/">software testing course</a>. That&#8217;s where I discovered the solution to <em>The Asserts Hell</em>.</p>



<h2 class="wp-block-heading">Assert Object for Better Asserts</h2>



<p>Assert Object pattern is what solves our problem. The idea is to create an <em>Assert</em> class which wraps the original object being tested. In our case the tested object is of <span style="color:#ff9f05" class="tadv-color">Product</span> class, so our assert class will be called <span style="color:#ff9f05" class="tadv-color">ProductAssert</span>.</p>



<p>Let&#8217;s see the implementation:</p>



<script src="https://gist.github.com/dsibinski/10a3c47a7e997eed29fabcb07914786b.js"></script>



<p>As you can see, we simply moved the asserts from our test&#8217;s Then section into <span style="color:#ff9f05" class="tadv-color">ProductAssert</span> class&#8217;s methods. Additionally, we always return <span style="color:#ff9f05" class="tadv-color">this</span> from each asserting method, which allows chaining functions calls.</p>



<p>We can now use such assert object<span style="color:#444" class="tadv-color"> in our</span> unit test: </p>



<script src="https://gist.github.com/dsibinski/e0a649e6134b9c6b389d3419db62f92a.js"></script>



<p>You must agree it&#8217;s much more readable now <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>We can of course improve it even more, for example by wrapping these 3 assertion methods (<span style="color:#ff9f05" class="tadv-color">BeAvailable()</span>, <span style="color:#ff9f05" class="tadv-color">HaveDiscount() </span><span style="color:#444" class="tadv-color">and</span><span style="color:#ff9f05" class="tadv-color"> Cost()</span>) into a single one. We can also easily create an <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods">extension method</a> for the <span style="color:#ff9f05" class="tadv-color">Product</span> class itself, so the assert object doesn&#8217;t have to be instantiated in our unit test. I could even add an extension to <em>FluentAssertions</em> library.</p>



<p>You can find complete source code used as examples in this article <a href="https://github.com/dsibinski/Playground/tree/main/Playground/Playground.Tests">here</a>.</p>



<h2 class="wp-block-heading">Assert Object &#8211; summary</h2>



<p>I personally find Assert Object a very useful tests code refactoring method. As a programmer, you spend most of your time not on writing, but on reading the source code. Clear and simple tests can make your (and your colleagues&#8217;) life much better <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>Of course, the Assert Object pattern should not be your default way of asserting. If you can complete your test with one or two assertions, then it&#8217;s probably better to keep it without wrapping into any additional objects. Having too many <em>assert</em> statements might also mean that the objects being tested are poorly designed. However, as we often work with legacy code which we can&#8217;t easily change or refactor, it might be a good solution.</p>



<p>What patterns for writing better tests do you use? Share your tips in the comments!</p>
<p>The post <a href="https://www.codejourney.net/improve-your-tests-with-assert-object-pattern/">Improve your tests with Assert Object Pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/improve-your-tests-with-assert-object-pattern/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3888</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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/08/TypeScript_prototype_functions_error.png?fit=300%2C67&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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>Basics of Flutter Widgets</title>
		<link>https://www.codejourney.net/basics-of-flutter-widgets/</link>
					<comments>https://www.codejourney.net/basics-of-flutter-widgets/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 16 Jan 2020 16:00:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[flutter]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3715</guid>

					<description><![CDATA[<p>What is a widget? If you ever worked with a web framework like React, you should know the concept of components. Flutter widgets are directly inspired by this idea. Widget is a reusable piece of code, which describes how your application&#8217;s UI looks like. Widgets define the user interface by their state. In some cases,&#8230;</p>
<p>The post <a href="https://www.codejourney.net/basics-of-flutter-widgets/">Basics of Flutter Widgets</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>After <a href="https://www.codejourney.net/2019/12/your-first-flutter-app-in-30-minutes/" target="_blank" rel="noopener noreferrer">writing our first Flutter app in less than 30 minutes</a>, today we&#8217;re taking a look at Flutter widgets. If you want to know what is a widget in Flutter, what are widgets types and how to use them &#8211; this article is for you <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-3715"></span>



<h2 class="wp-block-heading">What is a widget?</h2>



<p>If you ever worked with a web framework like <a rel="noreferrer noopener" aria-label="React (opens in a new tab)" href="https://reactjs.org/" target="_blank">React</a>, you should know the concept of <em>components</em>. Flutter widgets are directly inspired by this idea. Widget is a <strong>reusable piece of code, which describes how your application&#8217;s UI looks like</strong>. Widgets define the user interface by their <strong>state</strong>. In some cases, the state can be static and not change over time &#8211; see the <a href="#flutter-widget-types">section below about Flutter widget types</a> for details.</p>



<p>As soon as a widget&#8217;s state changes, Flutter rebuilds its outlook and in effect re-renders the GUI. The framework is said to do it efficiently by measuring what has changed in the widgets tree since the last rendering and re-paints only what&#8217;s necessary.</p>



<p>The most basic Flutter app might look 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="gist100539783" 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_simplest_app-dart" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-dart  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="main_simplest_app.dart content, created by dsibinski on 02:13AM on January 13, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="main_simplest_app.dart">
        <tr>
          <td id="file-main_simplest_app-dart-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-main_simplest_app-dart-LC1" class="blob-code blob-code-inner js-file-line">import &#39;package:flutter/material.dart&#39;;</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-main_simplest_app-dart-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-main_simplest_app-dart-LC3" class="blob-code blob-code-inner js-file-line">void main() =&gt; runApp(</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-main_simplest_app-dart-LC4" class="blob-code blob-code-inner js-file-line">      Center(</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-main_simplest_app-dart-LC5" class="blob-code blob-code-inner js-file-line">          child: Text(</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-main_simplest_app-dart-LC6" class="blob-code blob-code-inner js-file-line">        &quot;Hello Flutter!&quot;,</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-main_simplest_app-dart-LC7" class="blob-code blob-code-inner js-file-line">        textDirection: TextDirection.ltr,</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-main_simplest_app-dart-LC8" class="blob-code blob-code-inner js-file-line">      )),</td>
        </tr>
        <tr>
          <td id="file-main_simplest_app-dart-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-main_simplest_app-dart-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/e950a3cd710a539359a855752900c295/raw/23a6fec940a3c5e420ab9483a585f9ea495345d4/main_simplest_app.dart" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/e950a3cd710a539359a855752900c295#file-main_simplest_app-dart" class="Link--inTextBlock">
          main_simplest_app.dart
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>The<span style="color:#bb9d1b" class="tadv-color"> </span><span style="color:#f7bb1e" class="tadv-color">runApp()</span> method takes a <span style="color:#f7bb1e" class="tadv-color">Widget</span> as its argument. In our case, it takes a <span style="color:#f7bb1e" class="tadv-color">Center</span> widget, which has one child &#8211; a <span style="color:#f7bb1e" class="tadv-color">Text</span> widget. As expected, such a simple Flutter app shows a &#8220;Hello Flutter!&#8221; text at the center of the screen.</p>



<p>This simple example shows us a few interesting facts:</p>



<ul class="wp-block-list"><li>there are <strong>many built-in widgets</strong>, like <span style="color:#f7bb1e" class="tadv-color">Center</span> and <span style="color:#f7bb1e" class="tadv-color">Text</span></li><li><strong>widgets can have a child or children</strong> &#8211; this is <em>widgets nesting</em> and it happens all the time and can be very deep</li><li>Flutter <strong>widgets can have their own properties</strong>, like <span style="color:#f7bb1e" class="tadv-color">textDirection</span>.</li></ul>



<p>Widgets nesting sometimes makes simple Flutter apps having a lot of source code inside a single file. However, as I mentioned in <a rel="noreferrer noopener" aria-label="the previous post (opens in a new tab)" href="https://www.codejourney.net/2019/12/your-first-flutter-app-in-30-minutes/" target="_blank">the previous post</a>, don&#8217;t get discouraged by 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;" /> Actually, <strong>having a lot of nested widgets in Flutter is a good practice</strong>. If you have a few huge widgets without much nesting instead, it means that there&#8217;s something wrong with your implementation. Flutter widgets &#8211; as all reusable pieces of code &#8211; should not have too many responsibilities. <a rel="noreferrer noopener" aria-label="SOLID (opens in a new tab)" href="https://en.wikipedia.org/wiki/SOLID" target="_blank">SOLID</a> also applies here <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">Viewing Flutter widgets with Flutter Inspector</h2>



<p>As widgets tree may get big and quite heavily nested, there&#8217;s a very useful tool to easily view and explore it. This tool is called <a rel="noreferrer noopener" aria-label="Flutter Inspector (opens in a new tab)" href="https://flutter.dev/docs/development/tools/devtools/inspector" target="_blank">Flutter Inspector</a>.</p>



<p>While in debug mode in Visual Studio Code, you can launch it by clicking the blue magnifier icon:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="866" height="174" data-attachment-id="3727" data-permalink="https://www.codejourney.net/basics-of-flutter-widgets/image/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?fit=866%2C174&amp;ssl=1" data-orig-size="866,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="image" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?fit=300%2C60&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?fit=866%2C174&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?resize=866%2C174&#038;ssl=1" alt="Flutter Widgets: blue magnifier button in VS Code which opens the widgets inspector" class="wp-image-3727" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?w=866&amp;ssl=1 866w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?resize=300%2C60&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?resize=768%2C154&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image.png?resize=676%2C136&amp;ssl=1 676w" sizes="auto, (max-width: 866px) 100vw, 866px" /><figcaption>A button for opening Flutter Widgets Inspector from VS Code</figcaption></figure>



<p>It opens in a web browser and allows you to see the whole widgets tree in your app:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="1025" data-attachment-id="3728" data-permalink="https://www.codejourney.net/basics-of-flutter-widgets/image-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?fit=950%2C1025&amp;ssl=1" data-orig-size="950,1025" 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="image-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?fit=278%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?fit=950%2C1025&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?resize=950%2C1025&#038;ssl=1" alt="Flutter Widgets: Dart DevTools widgets inspector" class="wp-image-3728" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?w=950&amp;ssl=1 950w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?resize=278%2C300&amp;ssl=1 278w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?resize=768%2C829&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/image-1.png?resize=676%2C729&amp;ssl=1 676w" sizes="auto, (max-width: 950px) 100vw, 950px" /><figcaption>Flutter Inspector (part of Dart DevTools)</figcaption></figure>



<p>There&#8217;s a very handy feature &#8220;Select Widget Mode&#8221; which, when enabled, lets you select the widgets directly in your emulator or phone. After doing this, you can see the selected widget&#8217;s properties in the inspector.</p>



<h2 class="wp-block-heading" id="flutter-widget-types">Types of Flutter widgets</h2>



<p>In Flutter, you can &#8211; and will &#8211; create your own widgets. Widget is just a Dart class which extends a proper base class. Depending on whether your widget actually manages any state and changes over time, you have two types of base classes to inherit from &#8211; <a rel="noreferrer noopener" aria-label="StatelessWidget (opens in a new tab)" href="https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html" target="_blank">StatelessWidget</a> or <a rel="noreferrer noopener" aria-label="StatefulWidget (opens in a new tab)" href="https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html" target="_blank">StatefulWidget</a>.</p>



<p>The main purpose of each type of widget is to provide an implementation of a <span style="color:#f7bb1e" class="tadv-color">build() </span>method which returns a <span style="color:#f7bb1e" class="tadv-color">Widget</span> object. However, each widget type does it a bit differently. Let&#8217;s see this in action.</p>



<h3 class="wp-block-heading">StatelessWidgets</h3>



<p>The simplest widget you can create is a stateless widget. You create it by simply creating a class extending <a rel="noreferrer noopener" href="https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html" target="_blank">StatelessWidget</a>.  Here&#8217;s the sample source code and a view it generates:</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-embed alignwide"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist100563362" 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_stateless_widget-dart" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-dart  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="main_stateless_widget.dart content, created by dsibinski on 03:36AM on January 14, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="main_stateless_widget.dart">
        <tr>
          <td id="file-main_stateless_widget-dart-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-main_stateless_widget-dart-LC1" class="blob-code blob-code-inner js-file-line">import &#39;package:flutter/material.dart&#39;;</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-main_stateless_widget-dart-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-main_stateless_widget-dart-LC3" class="blob-code blob-code-inner js-file-line">void main() =&gt; runApp(</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-main_stateless_widget-dart-LC4" class="blob-code blob-code-inner js-file-line">      MaterialApp(</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-main_stateless_widget-dart-LC5" class="blob-code blob-code-inner js-file-line">        title: &quot;My CodeJourney Flutter app&quot;,</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-main_stateless_widget-dart-LC6" class="blob-code blob-code-inner js-file-line">        home: Scaffold(</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-main_stateless_widget-dart-LC7" class="blob-code blob-code-inner js-file-line">          appBar: AppBar(</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-main_stateless_widget-dart-LC8" class="blob-code blob-code-inner js-file-line">            title: Text(&quot;My First App&quot;),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-main_stateless_widget-dart-LC9" class="blob-code blob-code-inner js-file-line">          ),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-main_stateless_widget-dart-LC10" class="blob-code blob-code-inner js-file-line">          body: MyFirstWidget(),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-main_stateless_widget-dart-LC11" class="blob-code blob-code-inner js-file-line">        ),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-main_stateless_widget-dart-LC12" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-main_stateless_widget-dart-LC13" class="blob-code blob-code-inner js-file-line">    );</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-main_stateless_widget-dart-LC14" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-main_stateless_widget-dart-LC15" class="blob-code blob-code-inner js-file-line">class MyFirstWidget extends StatelessWidget {</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-main_stateless_widget-dart-LC16" class="blob-code blob-code-inner js-file-line">  @override</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-main_stateless_widget-dart-LC17" class="blob-code blob-code-inner js-file-line">  Widget build(BuildContext context) {</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-main_stateless_widget-dart-LC18" class="blob-code blob-code-inner js-file-line">    return Container(</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-main_stateless_widget-dart-LC19" class="blob-code blob-code-inner js-file-line">      padding: EdgeInsets.all(8.0),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-main_stateless_widget-dart-LC20" class="blob-code blob-code-inner js-file-line">      child: Text(</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-main_stateless_widget-dart-LC21" class="blob-code blob-code-inner js-file-line">        &quot;Hello MyFirstWidget!&quot;,</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
          <td id="file-main_stateless_widget-dart-LC22" class="blob-code blob-code-inner js-file-line">        style: TextStyle(color: Colors.green),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
          <td id="file-main_stateless_widget-dart-LC23" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
          <td id="file-main_stateless_widget-dart-LC24" class="blob-code blob-code-inner js-file-line">    );</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
          <td id="file-main_stateless_widget-dart-LC25" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-main_stateless_widget-dart-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
          <td id="file-main_stateless_widget-dart-LC26" 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/1a26fa1e212adbb858230f62183f7109/raw/28bd7f47b938fc6d295f3700c2550c5efe902b44/main_stateless_widget.dart" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/1a26fa1e212adbb858230f62183f7109#file-main_stateless_widget-dart" class="Link--inTextBlock">
          main_stateless_widget.dart
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image alignwide size-large"><img loading="lazy" decoding="async" width="1080" height="1920" data-attachment-id="3731" data-permalink="https://www.codejourney.net/basics-of-flutter-widgets/flutter_statelesswidget/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.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="Flutter_statelessWidget" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?fit=169%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?fit=576%2C1024&amp;ssl=1" src="https://i1.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?fit=576%2C1024&amp;ssl=1" alt="" class="wp-image-3731" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?w=1080&amp;ssl=1 1080w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?resize=864%2C1536&amp;ssl=1 864w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statelessWidget.png?resize=676%2C1202&amp;ssl=1 676w" sizes="auto, (max-width: 1080px) 100vw, 1080px" /></figure>


</div>
</div>



<p>You can play with it yourself <a rel="noreferrer noopener" aria-label="in the DartPad (opens in a new tab)" href="https://dartpad.dev/1a26fa1e212adbb858230f62183f7109" target="_blank">in the DartPad</a>.</p>



<p>There are quite a few new things in the source code. Let&#8217;s point them out:</p>



<ul class="wp-block-list"><li>as our main widget, we used <span style="color:#f7bb1e" class="tadv-color">MaterialApp</span> and provided it to <span style="color:#f7bb1e" class="tadv-color">runApp()</span> method. MaterialApp widget gives us material design for our app out of the box. As soon as you use it, you can nest more material widgets from the <a rel="noreferrer noopener" aria-label="widgets library (opens in a new tab)" href="https://flutter.dev/docs/development/ui/widgets/material" target="_blank">widgets library</a>. There&#8217;s a similar widget for Apple-oriented widgets called <a rel="noreferrer noopener" aria-label="CupertinoApp (opens in a new tab)" href="https://api.flutter.dev/flutter/cupertino/CupertinoApp-class.html" target="_blank">CupertinoApp</a>, which allows using <a rel="noreferrer noopener" aria-label="Cupertino widgets (opens in a new tab)" href="https://flutter.dev/docs/development/ui/widgets/cupertino" target="_blank">Cupertino widgets</a></li><li>we used another material widget &#8211; a <span style="color:#f7bb1e" class="tadv-color">Scaffold</span>. It provides us with an <span style="color:#f7bb1e" class="tadv-color">appBar</span> and <span style="color:#f7bb1e" class="tadv-color">body</span> properties &#8211; setting them we&#8217;re getting this nice-looking application&#8217;s skeleton with entitled app bar and home for our widget. Scaffold also gives us many things &#8220;for free&#8221;, e.g.  <a rel="noreferrer noopener" href="https://api.flutter.dev/flutter/material/FloatingActionButton-class.html" target="_blank">FloatingActionButton</a></li><li><span style="color:#f7bb1e" class="tadv-color">body</span> of our <span style="color:#f7bb1e" class="tadv-color">Scaffold</span> is our first own stateless widget &#8211; <span style="color:#f7bb1e" class="tadv-color">MyFirstWidget</span>. As mentioned before, it overrides the <span style="color:#f7bb1e" class="tadv-color">build()</span> method, which simply returns another widget tree. Notice the usage of a <span style="color:#f7bb1e" class="tadv-color">Container</span> widget, which is very useful for grouping other widgets.</li></ul>



<p>StatelessWidget is simple, works and is just there <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 something more interesting now &#8211; StatefulWidgets.</p>



<h3 class="wp-block-heading">StatefulWidgets</h3>



<p>When you want your widget to change over time and maintain its state (in most cases you do), you can create a stateful widget. You do it by creating a Dart class extending <a rel="noreferrer noopener" aria-label="StatefulWidget (opens in a new tab)" href="https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html" target="_blank">StatefulWidget</a>. Unlike StatelessWidgets, StatefulWidget doesn&#8217;t override the <span style="color:#f7bb1e" class="tadv-color">build()</span> method. Instead, it implements a <span style="color:#f7bb1e" class="tadv-color">createState()</span> method, which creates the initial widget&#8217;s state (see below).</p>



<p>Apart from the main widget class, which itself is still &#8220;final&#8221; (or better said &#8211; immutable), you create a class extending <a rel="noreferrer noopener" aria-label="State (opens in a new tab)" href="https://api.flutter.dev/flutter/widgets/State-class.html" target="_blank">State</a>. This class maintains the actual state and it is now who provides the <span style="color:#f7bb1e" class="tadv-color">build()</span> method&#8217;s implementation.</p>



<p>Let&#8217;s see the sample code and produced GUI:</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<figure class="wp-block-embed alignwide"><div class="wp-block-embed__wrapper">
<style>.gist table { margin-bottom: 0; }</style><div style="tab-size: 8" id="gist100605434" 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_stateful_widget-dart" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-dart  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="main_stateful_widget.dart content, created by dsibinski on 11:31PM on January 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="main_stateful_widget.dart">
        <tr>
          <td id="file-main_stateful_widget-dart-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-main_stateful_widget-dart-LC1" class="blob-code blob-code-inner js-file-line">class MySecondWidget extends StatefulWidget {</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-main_stateful_widget-dart-LC2" class="blob-code blob-code-inner js-file-line">  MySecondWidget({Key key}) : super(key: key);</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-main_stateful_widget-dart-LC3" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-main_stateful_widget-dart-LC4" class="blob-code blob-code-inner js-file-line">  @override</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-main_stateful_widget-dart-LC5" class="blob-code blob-code-inner js-file-line">  _MySecondWidgetState createState() =&gt; </td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-main_stateful_widget-dart-LC6" class="blob-code blob-code-inner js-file-line">                _MySecondWidgetState();</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-main_stateful_widget-dart-LC7" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-main_stateful_widget-dart-LC8" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-main_stateful_widget-dart-LC9" class="blob-code blob-code-inner js-file-line">class _MySecondWidgetState extends State&lt;MySecondWidget&gt; {</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-main_stateful_widget-dart-LC10" class="blob-code blob-code-inner js-file-line">  int _clickCount = 0;</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-main_stateful_widget-dart-LC11" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-main_stateful_widget-dart-LC12" class="blob-code blob-code-inner js-file-line">  void incrementClickCount() {</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-main_stateful_widget-dart-LC13" class="blob-code blob-code-inner js-file-line">    setState(() {</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-main_stateful_widget-dart-LC14" class="blob-code blob-code-inner js-file-line">      this._clickCount++;</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-main_stateful_widget-dart-LC15" class="blob-code blob-code-inner js-file-line">    });</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-main_stateful_widget-dart-LC16" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-main_stateful_widget-dart-LC17" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-main_stateful_widget-dart-LC18" class="blob-code blob-code-inner js-file-line">  @override</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-main_stateful_widget-dart-LC19" class="blob-code blob-code-inner js-file-line">  Widget build(BuildContext context) {</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-main_stateful_widget-dart-LC20" class="blob-code blob-code-inner js-file-line">    return Scaffold(</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-main_stateful_widget-dart-LC21" class="blob-code blob-code-inner js-file-line">      appBar: AppBar(</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
          <td id="file-main_stateful_widget-dart-LC22" class="blob-code blob-code-inner js-file-line">        title: Text(&quot;My First App&quot;),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
          <td id="file-main_stateful_widget-dart-LC23" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
          <td id="file-main_stateful_widget-dart-LC24" class="blob-code blob-code-inner js-file-line">      body: Container(</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
          <td id="file-main_stateful_widget-dart-LC25" class="blob-code blob-code-inner js-file-line">        padding: EdgeInsets.all(8.0),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
          <td id="file-main_stateful_widget-dart-LC26" class="blob-code blob-code-inner js-file-line">        child: Text(</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
          <td id="file-main_stateful_widget-dart-LC27" class="blob-code blob-code-inner js-file-line">          &quot;Hello! Times clicked: &quot; </td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
          <td id="file-main_stateful_widget-dart-LC28" class="blob-code blob-code-inner js-file-line">                + this._clickCount.toString(),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
          <td id="file-main_stateful_widget-dart-LC29" class="blob-code blob-code-inner js-file-line">          style: TextStyle(</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
          <td id="file-main_stateful_widget-dart-LC30" class="blob-code blob-code-inner js-file-line">            color: Colors.green, </td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
          <td id="file-main_stateful_widget-dart-LC31" class="blob-code blob-code-inner js-file-line">            fontSize: 20.0),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
          <td id="file-main_stateful_widget-dart-LC32" class="blob-code blob-code-inner js-file-line">        ),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
          <td id="file-main_stateful_widget-dart-LC33" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
          <td id="file-main_stateful_widget-dart-LC34" class="blob-code blob-code-inner js-file-line">      floatingActionButton: FloatingActionButton(</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
          <td id="file-main_stateful_widget-dart-LC35" class="blob-code blob-code-inner js-file-line">        child: Icon(Icons.add),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
          <td id="file-main_stateful_widget-dart-LC36" class="blob-code blob-code-inner js-file-line">        onPressed: this.incrementClickCount,</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
          <td id="file-main_stateful_widget-dart-LC37" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L38" class="blob-num js-line-number js-blob-rnum" data-line-number="38"></td>
          <td id="file-main_stateful_widget-dart-LC38" class="blob-code blob-code-inner js-file-line">    );</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L39" class="blob-num js-line-number js-blob-rnum" data-line-number="39"></td>
          <td id="file-main_stateful_widget-dart-LC39" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-main_stateful_widget-dart-L40" class="blob-num js-line-number js-blob-rnum" data-line-number="40"></td>
          <td id="file-main_stateful_widget-dart-LC40" 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/74e2318c87f611ce3b8e2f0dab817567/raw/55cbf4b0cf9f29e6f855c04d36a5a361bad588fc/main_stateful_widget.dart" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/74e2318c87f611ce3b8e2f0dab817567#file-main_stateful_widget-dart" class="Link--inTextBlock">
          main_stateful_widget.dart
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image alignwide size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="576" height="1024" data-attachment-id="3745" data-permalink="https://www.codejourney.net/basics-of-flutter-widgets/flutter_statefulwidget-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.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="Flutter_statefulWidget-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?fit=169%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?fit=576%2C1024&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?resize=576%2C1024&#038;ssl=1" alt="" class="wp-image-3745" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?resize=864%2C1536&amp;ssl=1 864w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?resize=676%2C1202&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_statefulWidget-1.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 576px) 100vw, 576px" /></figure>
</div>
</div>



<p>The full code you can play with is available <a rel="noreferrer noopener" aria-label="in the DartPad (opens in a new tab)" href="https://dartpad.dev/6a140d19910f60d03e8752b1a3b7f083" target="_blank">in the DartPad</a>.</p>



<p>Now some comments about the StatefulWidget code:</p>



<ul class="wp-block-list"><li>notice how <span style="color:#f7bb1e" class="tadv-color">MySecondWidget</span> class passes a <span style="color:#f7bb1e" class="tadv-color">key</span> to its superclass. Concept of Flutter widgets keys is interesting and we&#8217;ll dig into it in a separate post. For now, just treat it as a convention to always accept a <span style="color:#f7bb1e" class="tadv-color">key</span> as a named argument and pass it to the base class</li><li>as said before, in this simple example, <span style="color:#f7bb1e" class="tadv-color">MySecondWidget</span> only creates the initial state by instantiating <span style="color:#f7bb1e" class="tadv-color">_MySecondWidgetState</span></li><li>you&#8217;re already familiar with most of the code in <span style="color:#f7bb1e" class="tadv-color">_MySecondWidgetState</span>, but notice the usage of <span style="color:#f7bb1e" class="tadv-color">setState()</span> in <span style="color:#f7bb1e" class="tadv-color">incrementClickCount()</span> function. It tells Flutter that the state has changed, so the framework can re-render the UI. If you directly change the value of <span style="color:#f7bb1e" class="tadv-color">this._clickCount</span> without calling <span style="color:#f7bb1e" class="tadv-color">setState()</span>, GUI will not be updated until <span style="color:#f7bb1e" class="tadv-color">setState()</span> is called in some other place. We&#8217;ll talk more about state management techniques in Flutter in the future articles</li><li>note how easy it is to add a <span style="color:#f7bb1e" class="tadv-color">FloatingActionButton</span> thanks to using <a rel="noreferrer noopener" aria-label="Scaffold (opens in a new tab)" href="https://api.flutter.dev/flutter/material/Scaffold-class.html" target="_blank">Scaffold</a> material widget.</li></ul>



<p>That was easy and works nicely! You now know how to use both Flutter widget types <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Flutter quick actions in VS Code</h2>



<p>I&#8217;d like to share with you two easy tips for working with Flutter in Visual Studio Code. Both speed up the development nicely. It assumes that you configured VS Code properly (if not read <a href="https://www.codejourney.net/2019/12/your-first-flutter-app-in-30-minutes/" target="_blank" rel="noreferrer noopener" aria-label="this article (opens in a new tab)">this article</a>) and have Flutter extension installed.</p>



<h3 class="wp-block-heading">Ctrl + .</h3>



<p>First important keyboard shortcut is <em>Ctrl</em>+<em>.</em> (<em>Cmd</em>+<em>.</em> on Mac). It allows you to perform many element-contextual actions. For me it&#8217;s most useful for removing widgets or wrapping widgets with other ones:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="3760" data-permalink="https://www.codejourney.net/basics-of-flutter-widgets/flutter_quickactions/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_quickActions.png?fit=418%2C409&amp;ssl=1" data-orig-size="418,409" 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="Flutter_quickActions" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_quickActions.png?fit=300%2C294&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_quickActions.png?fit=418%2C409&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_quickActions.png?resize=314%2C307&#038;ssl=1" alt="" class="wp-image-3760" width="314" height="307" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_quickActions.png?w=418&amp;ssl=1 418w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_quickActions.png?resize=300%2C294&amp;ssl=1 300w" sizes="auto, (max-width: 314px) 100vw, 314px" /><figcaption>Quick Flutter actions in VS Code (Ctrl+.)</figcaption></figure></div>



<h3 class="wp-block-heading">Snippets for widgets creation</h3>



<p>Another useful feature are code snippets for creating widgets. You use them by starting to type their acronym in your <em>.dart</em> file. There are two acronyms for widgets creation &#8211; <em>stless</em> for <span style="color:#f7bb1e" class="tadv-color">StatelessWidget</span> and <em>stful</em> for <span style="color:#f7bb1e" class="tadv-color">StatefulWidget</span> scaffolding. The usage looks as follows:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="909" height="327" data-attachment-id="3763" data-permalink="https://www.codejourney.net/basics-of-flutter-widgets/flutter_snippets/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?fit=909%2C327&amp;ssl=1" data-orig-size="909,327" 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="Flutter_snippets" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?fit=300%2C108&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?fit=909%2C327&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?resize=909%2C327&#038;ssl=1" alt="" class="wp-image-3763" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?w=909&amp;ssl=1 909w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?resize=300%2C108&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?resize=768%2C276&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2020/01/Flutter_snippets.png?resize=676%2C243&amp;ssl=1 676w" sizes="auto, (max-width: 909px) 100vw, 909px" /><figcaption>Visual Studio Code &#8211; using Flutter snippets</figcaption></figure></div>



<h2 class="wp-block-heading">Most popular Flutter widgets</h2>



<p>I wanted to list you here some most popular Flutter widgets, but they are quite well described <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="https://flutter.dev/docs/development/ui/widgets-intro#basic-widgets" target="_blank">here</a>. You can also search through the <a rel="noreferrer noopener" aria-label="widgets library (opens in a new tab)" href="https://flutter.dev/docs/reference/widgets" target="_blank">widgets library</a>. We&#8217;ve also used quite few of them in our examples above <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">Community widgets</h2>



<p>Many more people are starting to use Flutter and they also create a lot of community widgets. You can find the Dart packages for Flutter on <a rel="noreferrer noopener" aria-label="pub.dev (opens in a new tab)" href="https://pub.dev/" target="_blank">pub.dev</a>. I also recommend checking the <a rel="noreferrer noopener" aria-label="Flutter Awesome website (opens in a new tab)" href="https://flutterawesome.com/" target="_blank">Flutter Awesome website</a> where the best Flutter widgets, libraries and other extensions are listed.</p>



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



<p>That&#8217;s it! You&#8217;ve just learned how to use stateless and stateful widgets in Flutter. We&#8217;ve also seen what&#8217;s the difference between them and what are some basic conventions in creating them. There&#8217;s a lot more to Flutter widgets and related topics, but these are topics for separate posts. I hope to publish more of them 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;" /></p>



<p>In my opinion, bringing components into the mobile world in the form of widgets is a very nice idea. They give quite a good separation of logic and GUI management. For sure it&#8217;s a fresh start, totally changing the way in which we think about mobile apps development. Components have done their job in the web world, so why would widgets not succeed in mobile apps? <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;" /> We&#8217;ll see!</p>



<p>What do you think? If you are interested in some particular topics related to Flutter &#8211; let me 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>The post <a href="https://www.codejourney.net/basics-of-flutter-widgets/">Basics of Flutter Widgets</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/basics-of-flutter-widgets/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3715</post-id>	</item>
		<item>
		<title>Your First Flutter App in 30 Minutes</title>
		<link>https://www.codejourney.net/your-first-flutter-app-in-30-minutes/</link>
					<comments>https://www.codejourney.net/your-first-flutter-app-in-30-minutes/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 04 Dec 2019 17:26:31 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[flutter]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3652</guid>

					<description><![CDATA[<p>You may know my past affair with Xamarin, which somehow died a natural death. In today&#8217;s post, we&#8217;re taking a look at Flutter. If you want to know what is Flutter and how to build your first Flutter app in less than 30 minutes (including installation time) &#8211; let&#8217;s jump right into it 😉 What&#8230;</p>
<p>The post <a href="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/">Your First Flutter App in 30 Minutes</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p>You may know my past <a rel="noreferrer noopener" aria-label="affair with Xamarin (opens in a new tab)" href="https://www.codejourney.net/xamarin/" target="_blank">affair with Xamarin</a>, which somehow died a natural death. In today&#8217;s post, we&#8217;re taking a look at Flutter. If you want to know what is Flutter and how to build your first Flutter app in less than 30 minutes (including installation time) &#8211; let&#8217;s jump right into 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>



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



<h2 class="wp-block-heading">What is Flutter?</h2>



<p>Flutter is an <strong>open-source</strong> platform and development kit created by Google. You can use it to create <strong>mobile (Android, iOS), desktop (Windows, Mac, Linux)</strong> and recently also <strong>web applications</strong>.</p>



<p>Flutter is quite new, as it&#8217;s <strong>first official version 1.0 was released in December 2018</strong>. Before, it was developed and used internally by Google for a few years.</p>



<p>Since this time, countless Flutter apps have been published. You can find their list for instance <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="https://itsallwidgets.com/" target="_blank">here</a>. One of the most well-known Flutter apps is <a href="https://youtu.be/jtYk3gWRSw0" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">Xianyu app created by Alibaba</a> and used by 50M+ people.</p>



<p>The main purposes of Flutter are claimed to be <strong>fast development</strong>, <strong>beautiful and consistent UIs</strong> and <strong>native performance on each platform</strong>.</p>



<h2 class="wp-block-heading">Dart as a programming language</h2>



<p>Flutter uses <strong><a rel="noreferrer noopener" aria-label="Dart (opens in a new tab)" href="https://dart.dev/" target="_blank">Dart</a> as a programming language</strong>. Why is that? Well, of course, Dart is also developed by Google <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;" /> However, one of the real reasons is believed to be performance. </p>



<p>As you probably know, Flutter is not the first (and not the last) cross-platform mobile development platform. Its main competitor is <a rel="noreferrer noopener" aria-label="React Native (opens in a new tab)" href="https://facebook.github.io/react-native/" target="_blank">React Native</a>, which uses JavaScript. Dart <strong>compiles to the given platform&#8217;s native machine code</strong>. Thanks to that, it doesn&#8217;t have to use a <a rel="noreferrer noopener" aria-label="JavaScript bridge (opens in a new tab)" href="https://hackernoon.com/understanding-react-native-bridge-concept-e9526066ddb8" target="_blank">JavaScript bridge</a> to interact with native components that React Native apps have to do. I don&#8217;t know how true this is in real life and how it helps with performance, but that is one of the reasons for using Dart as a programming language for Flutter apps.</p>



<p>Dart is a <strong>UI-oriented language</strong>. For C/C#/Java developers, Dart&#8217;s syntax will be rather familiar and easy to learn. It&#8217;s <strong>object-oriented</strong>, including support for classes and interfaces. The language is <strong>type-safe</strong>, meaning it combines static and runtime types checking.</p>



<p>Dart is supported by its <strong>virtual machine</strong>, which also provides &#8211; amongst others &#8211; a <strong>garbage collector</strong> (if you don&#8217;t know what the GC is, check out <a rel="noreferrer noopener" aria-label="this post (opens in a new tab)" href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank">this post</a>).</p>



<p>Here&#8217;s a simple program written in Dart:</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="gist99841306" 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-dart" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-dart  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="main.dart content, created by dsibinski on 02:03AM on December 04, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="main.dart">
        <tr>
          <td id="file-main-dart-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-main-dart-LC1" class="blob-code blob-code-inner js-file-line">main() {</td>
        </tr>
        <tr>
          <td id="file-main-dart-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-main-dart-LC2" class="blob-code blob-code-inner js-file-line">  var myCar = new Car(&quot;Cybertruck&quot;, new DateTime(2021, 01, 01));</td>
        </tr>
        <tr>
          <td id="file-main-dart-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-main-dart-LC3" class="blob-code blob-code-inner js-file-line">  myCar.describe();</td>
        </tr>
        <tr>
          <td id="file-main-dart-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-main-dart-LC4" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
        <tr>
          <td id="file-main-dart-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-main-dart-LC5" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main-dart-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-main-dart-LC6" class="blob-code blob-code-inner js-file-line">class Car {</td>
        </tr>
        <tr>
          <td id="file-main-dart-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-main-dart-LC7" class="blob-code blob-code-inner js-file-line">  String model;</td>
        </tr>
        <tr>
          <td id="file-main-dart-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-main-dart-LC8" class="blob-code blob-code-inner js-file-line">  DateTime productionDate;</td>
        </tr>
        <tr>
          <td id="file-main-dart-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-main-dart-LC9" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main-dart-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-main-dart-LC10" class="blob-code blob-code-inner js-file-line">  // Ctor: notice the syntactic sugar members&#39; assignment</td>
        </tr>
        <tr>
          <td id="file-main-dart-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-main-dart-LC11" class="blob-code blob-code-inner js-file-line">  Car(this.model, this.productionDate) {</td>
        </tr>
        <tr>
          <td id="file-main-dart-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-main-dart-LC12" class="blob-code blob-code-inner js-file-line">    // Some other ctor init code here</td>
        </tr>
        <tr>
          <td id="file-main-dart-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-main-dart-LC13" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-main-dart-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-main-dart-LC14" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-main-dart-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-main-dart-LC15" class="blob-code blob-code-inner js-file-line">  int get productionYear =&gt;</td>
        </tr>
        <tr>
          <td id="file-main-dart-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-main-dart-LC16" class="blob-code blob-code-inner js-file-line">      productionDate?.year;</td>
        </tr>
        <tr>
          <td id="file-main-dart-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-main-dart-LC17" class="blob-code blob-code-inner js-file-line">  </td>
        </tr>
        <tr>
          <td id="file-main-dart-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-main-dart-LC18" class="blob-code blob-code-inner js-file-line">  void describe() {</td>
        </tr>
        <tr>
          <td id="file-main-dart-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-main-dart-LC19" class="blob-code blob-code-inner js-file-line">    print(&#39;Car: $model, produced in $productionYear&#39;);</td>
        </tr>
        <tr>
          <td id="file-main-dart-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-main-dart-LC20" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-main-dart-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-main-dart-LC21" 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/62f21a6a9e62af732b28fceec1310f9c/raw/4cbb0678c4f0c12be9ea22990e08f9f4c481da3d/main.dart" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/62f21a6a9e62af732b28fceec1310f9c#file-main-dart" class="Link--inTextBlock">
          main.dart
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>You can play with the code yourself <a rel="noreferrer noopener" aria-label="in the DartPad (opens in a new tab)" href="https://dartpad.dev/62f21a6a9e62af732b28fceec1310f9c" target="_blank">in the DartPad</a>.</p>



<p>Another interesting feature that is possible thanks to Dart is the <em>hot reload</em>. We&#8217;ll explore it later, but it significantly speeds up the development and testing time.</p>



<p>If you want to learn more about Dart, check out <a rel="noreferrer noopener" aria-label="the official docs (opens in a new tab)" href="https://dart.dev/tutorials" target="_blank">the official docs</a>.</p>



<h2 class="wp-block-heading">Everything as a widget</h2>



<p>The main concept in building Flutter apps are <strong>widgets</strong>. In Flutter, <strong>everything is a widget</strong> &#8211; buttons, texts, menus, colors, themes, spacings and paddings. Even your Flutter app is a widget.</p>



<p>What&#8217;s very interesting is that Flutter doesn&#8217;t use platform native widgets. Instead, it <strong>provides its own set of widgets for each platform</strong>, e.g. <a rel="noreferrer noopener" aria-label="Material Design (opens in a new tab)" href="https://material.io/develop/flutter/" target="_blank">Material Design</a> for Android and <a rel="noreferrer noopener" aria-label="Cupertino widgets (opens in a new tab)" href="https://flutter.dev/docs/development/ui/widgets/cupertino" target="_blank">Cupertino widgets</a> for iOS. Additionally, as a programmer, <strong>you can create your own widgets</strong>. Thanks to that, all Flutter apps look pretty much the same on every Android/iOS version. You don&#8217;t need to worry about some UI elements changes between OS releases. At the same time, an app built using these widgets looks like native GUI.</p>



<p>Thanks to the widgets concept, <strong>Flutter apps can be easily personalized and branded</strong>. <a rel="noreferrer noopener" aria-label="Recent researches show (opens in a new tab)" href="https://learn.g2.com/mobile-app-development-trends" target="_blank">Recent researches show</a> that customers are now starting to prefer more specific-looking apps to standard and boring native-designed UIs.</p>



<p>The drawback which I see about widgets is that <strong>there&#8217;s normally A LOT of source code in Flutter apps</strong>. Don&#8217;t get confused straightaway <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">Installation and configuration</h2>



<p>Now, let&#8217;s get into the real work. It surprised me how easy it is to start working with Flutter. As you&#8217;ll see in a moment, you can build quite a nice-looking mobile app with Flutter in less than 30 minutes!</p>



<p>There are several possibilities to work with Flutter. You can easily <a rel="noreferrer noopener" aria-label="set up Android Studio or IntelliJ (opens in a new tab)" href="https://flutter.dev/docs/get-started/editor?tab=androidstudio" target="_blank">set up Android Studio or IntelliJ</a>. For example purposes, we&#8217;ll focus on <strong>running and debugging an Android application on Windows PC using Visual Studio Code</strong>. If you&#8217;re on Mac or Linux, check out a corresponding <a rel="noreferrer noopener" aria-label="official installation guide (opens in a new tab)" href="https://flutter.dev/docs/get-started/install" target="_blank">official installation guide</a>.</p>



<h3 class="wp-block-heading">Install Flutter and Android SDK</h3>



<p>The installation process is quite easy. Initially I wanted to describe it here for you, but actually the <a rel="noreferrer noopener" aria-label="official installation docs (opens in a new tab)" href="https://flutter.dev/docs/get-started/install" target="_blank">official installation docs</a> do it pretty 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;" /> I&#8217;ll just guide you through the steps below with links to the official installation guide.</p>



<p><strong>Install Flutter SDK</strong> <strong>and Android Studio</strong></p>



<p>First of all, install Flutter SDK and Android Studio (which is required for Android SDK) following <a rel="noreferrer noopener" aria-label="this installation guide (opens in a new tab)" href="https://flutter.dev/docs/get-started/install/windows" target="_blank">this installation guide</a>. The process is fairly easy and should not take more than 15 minutes. Remember about using <em>flutter doctor</em> command to verify if everything is installed correctly &#8211; it gives very clear messages. In the end, using VS Code and having Android phone connected in USB Debugging mode, your <em>flutter doctor</em> command should have an output similar to mine:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="867" height="240" data-attachment-id="3669" data-permalink="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/flutterdoctor_vscode_ok/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?fit=867%2C240&amp;ssl=1" data-orig-size="867,240" 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="FlutterDoctor_VSCode_OK" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?fit=300%2C83&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?fit=867%2C240&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?resize=867%2C240&#038;ssl=1" alt="Flutter App - flutter doctor proper result" class="wp-image-3669" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?w=867&amp;ssl=1 867w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?resize=300%2C83&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?resize=768%2C213&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/FlutterDoctor_VSCode_OK.png?resize=676%2C187&amp;ssl=1 676w" sizes="auto, (max-width: 867px) 100vw, 867px" /><figcaption>The correct output of <strong>flutter doctor</strong> command for VS Code (not Android Studio) development and Android phone connected in USB Debugging mode</figcaption></figure>



<h3 class="wp-block-heading">Configure Visual Studio Code</h3>



<p>The next step is to configure Visual Studio Code to be able to develop, compile, run and debug Flutter apps. You only need to install the Flutter extension, which is very well described <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="https://flutter.dev/docs/get-started/editor?tab=vscode" target="_blank">here</a>. It should also automatically install the <a rel="noreferrer noopener" aria-label="Dart VS Code extension (opens in a new tab)" href="https://marketplace.visualstudio.com/items?itemName=Dart-Code.dart-code" target="_blank">Dart VS Code extension</a> which adds Dart language support to VS Code.</p>



<h2 class="wp-block-heading">Your first Flutter app</h2>



<p>Now let&#8217;s finally create this first Flutter Android application <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 probably gonna be the quickest part!</p>



<h3 class="wp-block-heading">Create and run a sample app</h3>



<p>First of all, open Visual Studio Code. Use <em>Ctrl+Shift+P</em> to open a Command Palette. Start typing &#8220;Flutter&#8221; and select <em>Flutter: New Project</em>:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="831" height="252" data-attachment-id="3671" data-permalink="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/flutter_newproject_vscode/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?fit=831%2C252&amp;ssl=1" data-orig-size="831,252" 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="Flutter_NewProject_VSCode" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?fit=300%2C91&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?fit=831%2C252&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?resize=831%2C252&#038;ssl=1" alt="Flutter App - New Project creation in VS Code" class="wp-image-3671" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?w=831&amp;ssl=1 831w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?resize=300%2C91&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?resize=768%2C233&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_NewProject_VSCode.png?resize=676%2C205&amp;ssl=1 676w" sizes="auto, (max-width: 831px) 100vw, 831px" /></figure>



<p>In two next steps specify your project&#8217;s name (e.g. &#8220;hello_flutter&#8221;) and choose a location where the template should be generated.</p>



<p>Wait until VS Code generates the whole project and you see <em>main.dart</em> file in <em>lib</em> folder:</p>



<div class="wp-block-image"><figure class="aligncenter size-medium"><img data-recalc-dims="1" loading="lazy" decoding="async" width="159" height="300" data-attachment-id="3678" data-permalink="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/flutter_maindartfile-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_maindartfile-1.png?fit=221%2C416&amp;ssl=1" data-orig-size="221,416" 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="Flutter_maindartfile-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_maindartfile-1.png?fit=159%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_maindartfile-1.png?fit=221%2C416&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_maindartfile-1.png?resize=159%2C300&#038;ssl=1" alt="Flutter App - files structure of a template project with main.dart file" class="wp-image-3678" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_maindartfile-1.png?resize=159%2C300&amp;ssl=1 159w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_maindartfile-1.png?w=221&amp;ssl=1 221w" sizes="auto, (max-width: 159px) 100vw, 159px" /></figure></div>



<p>Open the <em>main.dart</em> file and replace its contents with the following, a bit cleaned-up code:</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="gist99854969" 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-flutter_demo_main-dart" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-dart  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="flutter_demo_main.dart content, created by dsibinski on 03:25PM on December 04, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="flutter_demo_main.dart">
        <tr>
          <td id="file-flutter_demo_main-dart-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-flutter_demo_main-dart-LC1" class="blob-code blob-code-inner js-file-line">import &#39;package:flutter/material.dart&#39;;</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
          <td id="file-flutter_demo_main-dart-LC2" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
          <td id="file-flutter_demo_main-dart-LC3" class="blob-code blob-code-inner js-file-line">void main() =&gt; runApp(HelloFlutterApp());</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
          <td id="file-flutter_demo_main-dart-LC4" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
          <td id="file-flutter_demo_main-dart-LC5" class="blob-code blob-code-inner js-file-line">class HelloFlutterApp extends StatelessWidget {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
          <td id="file-flutter_demo_main-dart-LC6" class="blob-code blob-code-inner js-file-line">  @override</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
          <td id="file-flutter_demo_main-dart-LC7" class="blob-code blob-code-inner js-file-line">  Widget build(BuildContext context) {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
          <td id="file-flutter_demo_main-dart-LC8" class="blob-code blob-code-inner js-file-line">    return MaterialApp(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
          <td id="file-flutter_demo_main-dart-LC9" class="blob-code blob-code-inner js-file-line">      title: &#39;HelloFlutter&#39;,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
          <td id="file-flutter_demo_main-dart-LC10" class="blob-code blob-code-inner js-file-line">      theme: ThemeData(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
          <td id="file-flutter_demo_main-dart-LC11" class="blob-code blob-code-inner js-file-line">        primarySwatch: Colors.lightGreen,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
          <td id="file-flutter_demo_main-dart-LC12" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
          <td id="file-flutter_demo_main-dart-LC13" class="blob-code blob-code-inner js-file-line">      home: MyHomePage(title: &#39;Hello Flutter!&#39;),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
          <td id="file-flutter_demo_main-dart-LC14" class="blob-code blob-code-inner js-file-line">    );</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
          <td id="file-flutter_demo_main-dart-LC15" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
          <td id="file-flutter_demo_main-dart-LC16" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
          <td id="file-flutter_demo_main-dart-LC17" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
          <td id="file-flutter_demo_main-dart-LC18" class="blob-code blob-code-inner js-file-line">class MyHomePage extends StatefulWidget {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
          <td id="file-flutter_demo_main-dart-LC19" class="blob-code blob-code-inner js-file-line">  MyHomePage({Key key, this.title}) : super(key: key);</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
          <td id="file-flutter_demo_main-dart-LC20" class="blob-code blob-code-inner js-file-line">  final String title;</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
          <td id="file-flutter_demo_main-dart-LC21" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
          <td id="file-flutter_demo_main-dart-LC22" class="blob-code blob-code-inner js-file-line">  @override</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
          <td id="file-flutter_demo_main-dart-LC23" class="blob-code blob-code-inner js-file-line">  _MyHomePageState createState() =&gt; _MyHomePageState();</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
          <td id="file-flutter_demo_main-dart-LC24" class="blob-code blob-code-inner js-file-line">}</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
          <td id="file-flutter_demo_main-dart-LC25" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
          <td id="file-flutter_demo_main-dart-LC26" class="blob-code blob-code-inner js-file-line">class _MyHomePageState extends State&lt;MyHomePage&gt; {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
          <td id="file-flutter_demo_main-dart-LC27" class="blob-code blob-code-inner js-file-line">  int _counter = 0;</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
          <td id="file-flutter_demo_main-dart-LC28" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
          <td id="file-flutter_demo_main-dart-LC29" class="blob-code blob-code-inner js-file-line">  void _incrementCounter() {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
          <td id="file-flutter_demo_main-dart-LC30" class="blob-code blob-code-inner js-file-line">    setState(() {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
          <td id="file-flutter_demo_main-dart-LC31" class="blob-code blob-code-inner js-file-line">      _counter++;</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
          <td id="file-flutter_demo_main-dart-LC32" class="blob-code blob-code-inner js-file-line">    });</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
          <td id="file-flutter_demo_main-dart-LC33" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
          <td id="file-flutter_demo_main-dart-LC34" class="blob-code blob-code-inner js-file-line">
</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
          <td id="file-flutter_demo_main-dart-LC35" class="blob-code blob-code-inner js-file-line">  @override</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
          <td id="file-flutter_demo_main-dart-LC36" class="blob-code blob-code-inner js-file-line">  Widget build(BuildContext context) {</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
          <td id="file-flutter_demo_main-dart-LC37" class="blob-code blob-code-inner js-file-line">    return Scaffold(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L38" class="blob-num js-line-number js-blob-rnum" data-line-number="38"></td>
          <td id="file-flutter_demo_main-dart-LC38" class="blob-code blob-code-inner js-file-line">      appBar: AppBar(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L39" class="blob-num js-line-number js-blob-rnum" data-line-number="39"></td>
          <td id="file-flutter_demo_main-dart-LC39" class="blob-code blob-code-inner js-file-line">        title: Text(widget.title),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L40" class="blob-num js-line-number js-blob-rnum" data-line-number="40"></td>
          <td id="file-flutter_demo_main-dart-LC40" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L41" class="blob-num js-line-number js-blob-rnum" data-line-number="41"></td>
          <td id="file-flutter_demo_main-dart-LC41" class="blob-code blob-code-inner js-file-line">      body: Center(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L42" class="blob-num js-line-number js-blob-rnum" data-line-number="42"></td>
          <td id="file-flutter_demo_main-dart-LC42" class="blob-code blob-code-inner js-file-line">        child: Column(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L43" class="blob-num js-line-number js-blob-rnum" data-line-number="43"></td>
          <td id="file-flutter_demo_main-dart-LC43" class="blob-code blob-code-inner js-file-line">          mainAxisAlignment: MainAxisAlignment.center,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L44" class="blob-num js-line-number js-blob-rnum" data-line-number="44"></td>
          <td id="file-flutter_demo_main-dart-LC44" class="blob-code blob-code-inner js-file-line">          children: &lt;Widget&gt;[</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L45" class="blob-num js-line-number js-blob-rnum" data-line-number="45"></td>
          <td id="file-flutter_demo_main-dart-LC45" class="blob-code blob-code-inner js-file-line">            Text(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L46" class="blob-num js-line-number js-blob-rnum" data-line-number="46"></td>
          <td id="file-flutter_demo_main-dart-LC46" class="blob-code blob-code-inner js-file-line">              &#39;You have pushed the button this many times: &#39;,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L47" class="blob-num js-line-number js-blob-rnum" data-line-number="47"></td>
          <td id="file-flutter_demo_main-dart-LC47" class="blob-code blob-code-inner js-file-line">            ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L48" class="blob-num js-line-number js-blob-rnum" data-line-number="48"></td>
          <td id="file-flutter_demo_main-dart-LC48" class="blob-code blob-code-inner js-file-line">            Text(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L49" class="blob-num js-line-number js-blob-rnum" data-line-number="49"></td>
          <td id="file-flutter_demo_main-dart-LC49" class="blob-code blob-code-inner js-file-line">              &#39;$_counter&#39;,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L50" class="blob-num js-line-number js-blob-rnum" data-line-number="50"></td>
          <td id="file-flutter_demo_main-dart-LC50" class="blob-code blob-code-inner js-file-line">              style: TextStyle(color: Colors.green, fontSize: 25),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L51" class="blob-num js-line-number js-blob-rnum" data-line-number="51"></td>
          <td id="file-flutter_demo_main-dart-LC51" class="blob-code blob-code-inner js-file-line">            ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L52" class="blob-num js-line-number js-blob-rnum" data-line-number="52"></td>
          <td id="file-flutter_demo_main-dart-LC52" class="blob-code blob-code-inner js-file-line">          ],</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L53" class="blob-num js-line-number js-blob-rnum" data-line-number="53"></td>
          <td id="file-flutter_demo_main-dart-LC53" class="blob-code blob-code-inner js-file-line">        ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L54" class="blob-num js-line-number js-blob-rnum" data-line-number="54"></td>
          <td id="file-flutter_demo_main-dart-LC54" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L55" class="blob-num js-line-number js-blob-rnum" data-line-number="55"></td>
          <td id="file-flutter_demo_main-dart-LC55" class="blob-code blob-code-inner js-file-line">      floatingActionButton: FloatingActionButton(</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L56" class="blob-num js-line-number js-blob-rnum" data-line-number="56"></td>
          <td id="file-flutter_demo_main-dart-LC56" class="blob-code blob-code-inner js-file-line">        onPressed: _incrementCounter,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L57" class="blob-num js-line-number js-blob-rnum" data-line-number="57"></td>
          <td id="file-flutter_demo_main-dart-LC57" class="blob-code blob-code-inner js-file-line">        tooltip: &#39;Increment&#39;,</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L58" class="blob-num js-line-number js-blob-rnum" data-line-number="58"></td>
          <td id="file-flutter_demo_main-dart-LC58" class="blob-code blob-code-inner js-file-line">        child: Icon(Icons.add),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L59" class="blob-num js-line-number js-blob-rnum" data-line-number="59"></td>
          <td id="file-flutter_demo_main-dart-LC59" class="blob-code blob-code-inner js-file-line">      ),</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L60" class="blob-num js-line-number js-blob-rnum" data-line-number="60"></td>
          <td id="file-flutter_demo_main-dart-LC60" class="blob-code blob-code-inner js-file-line">    );</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L61" class="blob-num js-line-number js-blob-rnum" data-line-number="61"></td>
          <td id="file-flutter_demo_main-dart-LC61" class="blob-code blob-code-inner js-file-line">  }</td>
        </tr>
        <tr>
          <td id="file-flutter_demo_main-dart-L62" class="blob-num js-line-number js-blob-rnum" data-line-number="62"></td>
          <td id="file-flutter_demo_main-dart-LC62" 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/9b10fa31f0d050979a03404eb7a75c73/raw/baea3b034734c06fb994663d8716e594d24b7194/flutter_demo_main.dart" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/9b10fa31f0d050979a03404eb7a75c73#file-flutter_demo_main-dart" class="Link--inTextBlock">
          flutter_demo_main.dart
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>We won&#8217;t focus on the source code here &#8211; I hope to dig more 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;" /> Just notice there are quite a few widgets &#8211; can you count them all? <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;" /> I found at least 12 different widgets used in this small template code.</p>



<p>Now the best part &#8211; having your Android phone connected (you should see it in the right-bottom corner of VS Code) press F5 to run the application. After a few seconds (usually longer for the first time) you should see this beautiful application on your smartphone&#8217;s screen:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="3679" data-permalink="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/flutter-firstandroidapp/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?fit=1080%2C2280&amp;ssl=1" data-orig-size="1080,2280" 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="Flutter-FirstAndroidApp" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?fit=142%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?fit=485%2C1024&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=364%2C768&#038;ssl=1" alt="Flutter App - first Flutter app (Android)" class="wp-image-3679" width="364" height="768" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=485%2C1024&amp;ssl=1 485w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=142%2C300&amp;ssl=1 142w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=768%2C1621&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=728%2C1536&amp;ssl=1 728w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=970%2C2048&amp;ssl=1 970w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?resize=676%2C1427&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter-FirstAndroidApp.jpg?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 364px) 100vw, 364px" /></figure></div>



<p>As soon as you press the &#8220;+&#8221; button the green counter increments. Yaaaaay! <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;" /></p>



<h3 class="wp-block-heading">Debug your Flutter app</h3>



<p>Now, try putting a breakpoint in <em>main.dart</em> file at line 30 (beginning of <em>_incrementCounter()</em> function). When you click the &#8220;+&#8221; button next time, VS Code should stop at the breakpoint:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" loading="lazy" decoding="async" width="867" height="306" data-attachment-id="3686" data-permalink="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/flutter_vscode_debug/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?fit=867%2C306&amp;ssl=1" data-orig-size="867,306" 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="Flutter_VSCode_Debug" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?fit=300%2C106&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?fit=867%2C306&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?resize=867%2C306&#038;ssl=1" alt="Dart's breakpoint hit in VS Code" class="wp-image-3686" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?w=867&amp;ssl=1 867w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?resize=300%2C106&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?resize=768%2C271&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_VSCode_Debug.png?resize=676%2C239&amp;ssl=1 676w" sizes="auto, (max-width: 867px) 100vw, 867px" /></figure>



<h3 class="wp-block-heading">Try hot reload</h3>



<p>The best for the end. As I mentioned before, Flutter lets you use a <a rel="noreferrer noopener" aria-label="hot reload (opens in a new tab)" href="https://flutter.dev/docs/development/tools/hot-reload" target="_blank">hot reload</a>. It lets you <strong>change the code while running the app and see the changes immediately</strong> after saving the source code file. I love it especially because it&#8217;s a <strong>stateful hot reload</strong>, meaning that except UI the state is also reloaded (or rather kept).</p>



<p>With your Flutter app running in debug mode, click the &#8220;+&#8221; button several times so the counter has value &gt; 0. Then go directly into VS Code and modify line 50 by changing the counter text color from <em>Colors.green</em> to  <em>Colors.red</em>. Line 50 should now look 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="gist99855426" 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-flutter_demo_main_line50_color-dart" class="file my-2">
    
    <div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-dart  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="flutter_demo_main_line50_color.dart content, created by dsibinski on 03:50PM on December 04, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="flutter_demo_main_line50_color.dart">
        <tr>
          <td id="file-flutter_demo_main_line50_color-dart-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
          <td id="file-flutter_demo_main_line50_color-dart-LC1" class="blob-code blob-code-inner js-file-line">style: TextStyle(color: Colors.red, fontSize: 25),</td>
        </tr>
  </table>
</div>


    </div>

  </div>
</div>

      </div>
      <div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/1a2cc4d1a176a22531807e87261dd6ea/raw/39a2c2aa97e5b3f34a9be63f7cef83c4eac5be06/flutter_demo_main_line50_color.dart" style="float:right" class="Link--inTextBlock">view raw</a>
        <a href="https://gist.github.com/dsibinski/1a2cc4d1a176a22531807e87261dd6ea#file-flutter_demo_main_line50_color-dart" class="Link--inTextBlock">
          flutter_demo_main_line50_color.dart
        </a>
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
    </div>
</div>

</div></figure>



<p>Save <em>main.dart</em> file by pressing Ctrl+S. Take a look at your smartphone and see the magic:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" data-attachment-id="3689" data-permalink="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/flutter_hotreload-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?fit=1080%2C2280&amp;ssl=1" data-orig-size="1080,2280" 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="Flutter_HotReload-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?fit=142%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?fit=485%2C1024&amp;ssl=1" src="https://i1.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?fit=485%2C1024&amp;ssl=1" alt="Flutteer's hot reload in action" class="wp-image-3689" width="364" height="768" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?w=1080&amp;ssl=1 1080w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?resize=142%2C300&amp;ssl=1 142w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?resize=485%2C1024&amp;ssl=1 485w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?resize=768%2C1621&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?resize=728%2C1536&amp;ssl=1 728w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?resize=970%2C2048&amp;ssl=1 970w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/12/Flutter_HotReload-1.jpg?resize=676%2C1427&amp;ssl=1 676w" sizes="auto, (max-width: 364px) 100vw, 364px" /></figure></div>



<p>Notice how the color of number &#8220;7&#8221; (counter value) changed to red while its value remains untouched. Quite a nice feature for quick development <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>I noticed that sometimes it doesn&#8217;t work that smoothly and you need to restart the app to see the changes. However, it happens only with some bigger code changes. Flutter quite young SDK and tools are still developing quickly so I hope such drawbacks will be eliminated soon.</p>



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



<p>Today we&#8217;ve seen how easy it is to start working with Flutter. We got familiar with basic Flutter concepts like widgets. We&#8217;ve also created our first Flutter app and debugged it. Finally, we&#8217;ve seen the very cool hot reload feature in action <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>For me, Flutter looks promising. After my adventures with <a rel="noreferrer noopener" aria-label="Xamarin (opens in a new tab)" href="https://www.codejourney.net/xamarin/" target="_blank">Xamarin</a>, which mostly felt like changing Java to C# and Android Studio to Visual Studio, I&#8217;m excited to try something fresh and totally different.</p>



<p>I know this was just a simple introduction to Flutter, but there&#8217;s more coming! I hope to publish the next articles about Flutter as I continue playing with it. If you&#8217;ve ever used Flutter and have some good sources to recommend &#8211; let me know in the comments!</p>



<p>Stay tuned!</p>


<p>The post <a href="https://www.codejourney.net/your-first-flutter-app-in-30-minutes/">Your First Flutter App in 30 Minutes</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/your-first-flutter-app-in-30-minutes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3652</post-id>	</item>
		<item>
		<title>How to Start Working with an Unknown Codebase?</title>
		<link>https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/</link>
					<comments>https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 02 Oct 2019 15:00:53 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[debugging]]></category>
		<guid isPermaLink="false">https://www.codejourney.net/?p=3584</guid>

					<description><![CDATA[<p>Understand the architecture For me, the first thing to do in a new project is to understand the software architecture. My goal here is to as quickly as possible find answers to the following questions: what is a client? Is it a desktop, mobile app or both? Maybe there&#8217;s only a web app, but used&#8230;</p>
<p>The post <a href="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/">How to Start Working with an Unknown Codebase?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you&#8217;ve ever joined a new project you probably know the excitement of being presented with a brand new source code. As soon as you&#8217;re assigned your first tasks the excitement turns into frustration, because it&#8217;s not easy to fix this simple bug&#8230; Even you&#8217;re an experienced developer.</p>
<p>Today I&#8217;m trying to address the issue of <strong>approaching an unknown codebase</strong>. I&#8217;ll give you some advices and tricks I&#8217;m using to make new code easier and quicker to understand &#8211; even without understanding it 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>



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



<h2 class="wp-block-heading">Understand the architecture</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="6016" height="4016" data-attachment-id="3618" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/software_architecture/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?fit=6016%2C4016&amp;ssl=1" data-orig-size="6016,4016" 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="software_architecture" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?fit=300%2C200&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?fit=1024%2C684&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?fit=676%2C452&amp;ssl=1" alt="How to start working with an unknown codebase: people standing by whiteboard drawing software architecture" class="wp-image-3618" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?w=6016&amp;ssl=1 6016w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?resize=768%2C513&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?resize=1024%2C684&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?resize=676%2C451&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/software_architecture.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>For me, the first thing to do in a new project is to understand the software architecture. My goal here is to as quickly as possible find answers to the following questions:</p>



<ul class="wp-block-list"><li>what is a <em>client</em>? Is it a <strong>desktop, mobile app or both</strong>? Maybe there&#8217;s only a web app, but used on different devices?</li><li>what is a <em>server</em>? Is it a <strong>single instance or some distributed service</strong>? Where does it run?</li><li>how do the <em>client and the server communicate</em>? Is there any framework used (e.g. WCF) or maybe just some RESTful web service communication?</li><li>are there any <em>architectural design patterns</em> used by the team in both clients and server apps (e.g. <strong>Layered Pattern, MVC, MVVM, CQRS</strong>&#8230;)?</li><li>what are the <em>important frameworks/libraries</em> used in the clients and server apps? By <em>important</em> I mean these ones which directly define the style of coding, for instance: <strong>ASP.NET MVC, WPF, Caliburn.Micro, Prism, Spring, Angular, React, TypeScript</strong> etc.</li></ul>



<p>Answering these few questions will give you a <em>feeling of where is what</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;" /> When working with some tasks you&#8217;ll automagically feel where the issue may be or where to look for a solution (or problem <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f62c.png" alt="😬" class="wp-smiley" style="height: 1em; max-height: 1em;" />).</p>



<p>It&#8217;s sometimes helpful to draw the architecture on a paper or whiteboard to help you easier grasp the elements and connections between them.</p>



<h2 class="wp-block-heading">Learn the persistence</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="6016" height="4016" data-attachment-id="3616" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/database/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?fit=6016%2C4016&amp;ssl=1" data-orig-size="6016,4016" 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="database" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?fit=300%2C200&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?fit=1024%2C684&amp;ssl=1" src="https://i1.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?fit=676%2C452&amp;ssl=1" alt="How to start working with an unknown codebase: database servers" class="wp-image-3616" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?w=6016&amp;ssl=1 6016w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?resize=768%2C513&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?resize=1024%2C684&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?resize=676%2C451&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/database.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>Each application stores its data somewhere and you should know where and how it does it. At least it&#8217;s a bit helpful <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;" /></p>



<p>First of all, find out <strong>what kind of database is used</strong> by the software. Then check how the applications (clients, server) communicate with the database. In other words: find out <strong>in which place the queries are sent to the database</strong>. I really mean it &#8211; if SQL db is used, find out where exactly the SQL statements are generated and sent to the server. Maybe there&#8217;s some ORM (like Hibernate/NHibernate or Entity Framework) used for that?</p>



<p>Next, find out <strong>how is the persistent data (e.g. tables) represented in code</strong>. Where are the persistent classes defined? How are database restrictions (not-null fields, primary and foreign keys, constraints, data types) defined on them? How are the objects&#8217; fields <strong>mapped</strong> to database tables&#8217; columns?</p>



<p>In the end, try to understand how these persistent objects are presented in the GUI. Are there any <a rel="noreferrer noopener" aria-label="DTO objects (opens in a new tab)" href="https://en.wikipedia.org/wiki/Data_transfer_object" target="_blank">DTO objects</a> used? How is a <strong>business validation</strong> (e.g. maximal length of a field or email validator) defined for these objects (maybe some validation library is used)?</p>



<p>Knowing the persistence layer and its functioning in the software will help you work with your new, yet unknown codebase. You can often be assigned to issues related to database limitations or business validation and knowing where is what can significantly ease your pain <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">Learn to deploy your system</h2>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="960" height="220" data-attachment-id="3628" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/installation-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?fit=960%2C220&amp;ssl=1" data-orig-size="960,220" 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="Installation-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?fit=300%2C69&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?fit=960%2C220&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?resize=960%2C220&#038;ssl=1" alt="Application installation bar indicator" class="wp-image-3628" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?w=960&amp;ssl=1 960w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?resize=300%2C69&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?resize=768%2C176&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/Installation-1.png?resize=676%2C155&amp;ssl=1 676w" sizes="auto, (max-width: 960px) 100vw, 960px" /></figure>



<p>It may sound obvious, but you should quickly learn by heart how to deploy your system (or part of the system you are working on) from scratch.</p>



<p><strong>Compile the whole code and learn how to run it all</strong> (server and all clients). <strong>If possible, start with a clean database as a new customer would</strong>. If the process is complex write down the step-by-step instructions while your colleague explains the process to you. It&#8217;s very important that you practice it yourself and finally are able to go through this &#8220;deployment&#8221; process even without your notes. </p>



<h2 class="wp-block-heading">Know the system functionally</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="4000" height="2191" data-attachment-id="3615" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/system_functional_training/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?fit=4000%2C2191&amp;ssl=1" data-orig-size="4000,2191" 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_functional_training" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?fit=300%2C164&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?fit=1024%2C561&amp;ssl=1" src="https://i2.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?fit=676%2C370&amp;ssl=1" alt="How to start working with an unknown codebase: functional training meeting" class="wp-image-3615" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?w=4000&amp;ssl=1 4000w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?resize=300%2C164&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?resize=768%2C421&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?resize=1024%2C561&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?resize=676%2C370&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/system_functional_training.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>Among the first steps for approaching an unknown codebase you should&#8230; put the code aside and focus at least a bit on the <strong>functional side</strong>.</p>



<p>As soon as the whole system is running, spend some time clicking through the application. Try to grasp how it works, what&#8217;s the <em>feeling</em> of the system.</p>



<p>If possible, find someone who has functional knowledge about the software &#8211; preferably a consultant or customers&#8217; trainer &#8211; and ask him/her for a <strong>live demo</strong>. It would be best if they can give you an introductory demo as they do for end customers. Ask as many questions as come to your mind during such a presentation. If possible, leave some communication channels open with the person who trained you, e.g. a chat where you can leave your potential doubts/questions. Ask him/her to answer them from time to time. Also, check with the presenter if there are any resources on the <strong>problem domain of the system</strong>. </p>



<p>The better you understand the problem domain, the better your technical decisions are going to be. Sometimes you don&#8217;t need to understand everything &#8211; even consultants or designers may not always know what clients are really using the system for. However, it&#8217;s important to understand as much as possible from a functional point of view. Such a perspective helps you think differently when you&#8217;re asked to implement a feature that initially sounds like nonsense. Maybe that&#8217;s really what customers need to solve their domain problems? <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">Explore source code tests</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="4288" height="2848" data-attachment-id="3621" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/sourcecode_tests/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?fit=4288%2C2848&amp;ssl=1" data-orig-size="4288,2848" 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="sourcecode_tests" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?fit=300%2C199&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?fit=1024%2C680&amp;ssl=1" src="https://i1.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?fit=676%2C449&amp;ssl=1" alt="How to start working with an unknown codebase: source code with unit tests" class="wp-image-3621" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?w=4288&amp;ssl=1 4288w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?resize=300%2C199&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?resize=768%2C510&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?resize=1024%2C680&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?resize=676%2C449&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/sourcecode_tests.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>This part becomes more meaningful when you&#8217;re assigned your first tasks. I don&#8217;t recommend exploring all the tests in your application before you start working &#8211; except if these tests are veeeeery good and really human-readable (which I&#8217;ve honestly never seen so far <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>As soon as you&#8217;re starting to work on some task you may have the feeling that you completely have no idea how the related part of the software works. If that&#8217;s the case, <strong>try to look for tests (unit, integration tests) in the code related to this feature</strong>. If your &#8220;issue&#8221; is related to a need to make some changes in a particular method, try to find this method&#8217;s usages &#8211; hopefully, it&#8217;s called by some tests:</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="826" height="339" data-attachment-id="3602" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/vs_findreferences_tests/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?fit=826%2C339&amp;ssl=1" data-orig-size="826,339" 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_FindReferences_tests" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?fit=300%2C123&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?fit=826%2C339&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?resize=826%2C339&#038;ssl=1" alt="How to start working with an unknown codebase: finding method's usages in Visual Studio" class="wp-image-3602" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?w=826&amp;ssl=1 826w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?resize=300%2C123&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?resize=768%2C315&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_FindReferences_tests.png?resize=676%2C277&amp;ssl=1 676w" sizes="auto, (max-width: 826px) 100vw, 826px" /><figcaption>Visual Studio &#8211; finding references to a method</figcaption></figure>



<p>Exploring the tests can give you an idea of what an author-developer had on his/her mind when writing this code.</p>



<p>Of course, as soon as you make any changes in the code, run all tests to make sure you didn&#8217;t break anything <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 tests related to what you&#8217;ve changed. The best obviously is when you have a build server that runs the tests for you.</p>



<h2 class="wp-block-heading">Have software documentation around</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="2592" height="1728" data-attachment-id="3614" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/documentation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?fit=2592%2C1728&amp;ssl=1" data-orig-size="2592,1728" 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="documentation" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?fit=300%2C200&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?fit=1024%2C683&amp;ssl=1" src="https://i1.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?fit=676%2C451&amp;ssl=1" alt="How to start working with an unknown codebase: paper documentation" class="wp-image-3614" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?w=2592&amp;ssl=1 2592w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?resize=1024%2C683&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?resize=676%2C451&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/documentation.jpg?w=2280&amp;ssl=1 2280w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>If there&#8217;s any documentation for your new software &#8211; have it somewhere around. <strong>Don&#8217;t read it</strong> &#8211; except, again, if it&#8217;s veeeeery good and interesting (anyone has ever seen such docs?! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f602.png" alt="😂" class="wp-smiley" style="height: 1em; max-height: 1em;" />). <strong>Just keep it in case you need to find out how something works</strong>. You can always search such documentation by phrases/keywords related to the task you&#8217;re working on. Maybe it&#8217;ll help you to at least reproduce the problem <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">Document your actions</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="5760" height="3840" data-attachment-id="3610" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/writing_things_down-1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?fit=5760%2C3840&amp;ssl=1" data-orig-size="5760,3840" 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="writing_things_down-1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?fit=300%2C200&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?fit=1024%2C683&amp;ssl=1" src="https://i1.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?fit=676%2C451&amp;ssl=1" alt="How to start working with an unknown codebase: writing things in the notepad next to the laptop" class="wp-image-3610" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?w=5760&amp;ssl=1 5760w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?resize=300%2C200&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?resize=768%2C512&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?resize=1024%2C683&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?resize=676%2C451&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/writing_things_down-1.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>When I work with an unknown codebase I tend to <strong>keep track of what I&#8217;m doing</strong>. This is also one of my <a rel="noreferrer noopener" aria-label="productivity tricks (opens in a new tab)" href="https://www.codejourney.net/2017/03/simple-habits-for-better-productivity/" target="_blank">productivity tricks</a>. I create a new project in Nozbe (tasks/projects management application which I&#8217;m using) for each task I start working on. It can also be a new Notepad file, a new tab in Sublime Text or just a piece of paper. In such a place I write down what I&#8217;m currently working on. If I have some exception&#8217;s stacktrace I&#8217;m trying to analyze &#8211; I paste it there. I write down some objects and try to picture the relations between them.</p>



<p>Simply writing down stuff in a &#8220;natural language&#8221; often helps me find a solution quicker. Have you ever started to ask someone for help and as soon as you explained to him/her your issue, you suddenly got an idea of how to solve it? It works similarly with writing things down &#8211; it&#8217;s like explaining stuff to yourself. Just give it a try <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">Debug</h2>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="850" height="430" data-attachment-id="3603" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/vs_breakpoint_startup/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?fit=850%2C430&amp;ssl=1" data-orig-size="850,430" 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_breakpoint_startup" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?fit=300%2C152&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?fit=850%2C430&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?resize=850%2C430&#038;ssl=1" alt="How to start working with an unknown codebase: breakpoinit in Visual Studio" class="wp-image-3603" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?w=850&amp;ssl=1 850w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?resize=300%2C152&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?resize=768%2C389&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/VS_breakpoint_startup.png?resize=676%2C342&amp;ssl=1 676w" sizes="auto, (max-width: 850px) 100vw, 850px" /><figcaption>Breakpoint in one of MVC application&#8217;s startup methods</figcaption></figure>



<p>Obvious, right? Well, not necessarily. I often see people debug only when they know exactly what to debug. When working with an unknown codebase I find it helpful to <strong>break through the application&#8217;s startup</strong>. Put a few breakpoints in one of the application&#8217;s entry methods and debug how it launches and initializes line-by-line. </p>



<p>It will help you to see <strong>what components are used and how are these loaded</strong>. </p>



<p>Do the same with given actions you want to understand. If there&#8217;s some button that causes an issue later on (not directly after pressing it), put a breakpoint in a method that is assigned to a button and try to debug step-by-step until the exception is thrown. It will let you understand how the codebase is built and what the developer exactly intended to do with this button.</p>



<h2 class="wp-block-heading">Search literally</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="6016" height="4000" data-attachment-id="3620" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/searching/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?fit=6016%2C4000&amp;ssl=1" data-orig-size="6016,4000" 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="searching" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?fit=300%2C199&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?fit=1024%2C681&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?fit=676%2C450&amp;ssl=1" alt="How to start working with an unknown codebase: Google search" class="wp-image-3620" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?w=6016&amp;ssl=1 6016w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?resize=300%2C199&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?resize=768%2C511&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?resize=1024%2C681&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?resize=676%2C449&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/searching.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>I think most of us do that, but very few confess <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f602.png" alt="😂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>When working with an unknown codebase I very often <strong>search for things literally.</strong> For instance, when working on an issue occurring on pressing a button it may not be easy to find the code-behind the button (a method which executes as soon as you click it). In such a case, I just <strong>copy the text which is a button&#8217;s text or name and search by it literally in the whole codebase</strong>. It can even be one of the translated resources &#8211; their values are often stored somewhere (e.g. in XML files). This often allows to quickly identify a method attached to the button just by finding the string or the translation key&#8217;s usages <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>If you don&#8217;t have any GUI element with text to search for, try to <strong>search by intuition</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;" /> For example if you&#8217;re trying to find a code that handles saving a document, just search by strings like &#8220;SaveDocument&#8221;, &#8220;AddDocument&#8221;, &#8220;UpdateDocument&#8221; etc. It can greatly help you find what you need!</p>



<p>If you&#8217;re using Visual Studio with <a rel="noreferrer noopener" aria-label="ReSharper (opens in a new tab)" href="https://www.jetbrains.com/resharper/" target="_blank">ReSharper</a> there&#8217;s a really useful &#8220;Search everywhere&#8221; feature which allows you to easily search strings literally in the whole solution:</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="552" height="134" data-attachment-id="3631" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/resharper_searcheverywhere/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/resharper_searchEverywhere.png?fit=552%2C134&amp;ssl=1" data-orig-size="552,134" 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_searchEverywhere" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/resharper_searchEverywhere.png?fit=300%2C73&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/resharper_searchEverywhere.png?fit=552%2C134&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/resharper_searchEverywhere.png?resize=552%2C134&#038;ssl=1" alt="" class="wp-image-3631" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/resharper_searchEverywhere.png?w=552&amp;ssl=1 552w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/resharper_searchEverywhere.png?resize=300%2C73&amp;ssl=1 300w" sizes="auto, (max-width: 552px) 100vw, 552px" /><figcaption>ReSharper&#8217;s <a href="https://www.jetbrains.com/help/resharper/Navigation_and_Search__Go_to_Type.html" target="_blank" rel="noreferrer noopener" aria-label="search everywhere functionality (opens in a new tab)">search everywhere functionality</a></figcaption></figure>



<h2 class="wp-block-heading">Don&#8217;t be afraid to ask</h2>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="4000" height="2838" data-attachment-id="3606" data-permalink="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/asking_questions/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?fit=4000%2C2838&amp;ssl=1" data-orig-size="4000,2838" 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="asking_questions" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?fit=300%2C213&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?fit=1024%2C727&amp;ssl=1" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?fit=676%2C480&amp;ssl=1" alt="How to start working with an unknown codebase: man explaining stuff to a woman" class="wp-image-3606" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?w=4000&amp;ssl=1 4000w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?resize=300%2C213&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?resize=768%2C545&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?resize=1024%2C727&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?resize=676%2C480&amp;ssl=1 676w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?w=2280&amp;ssl=1 2280w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/10/asking_questions.jpg?w=3420&amp;ssl=1 3420w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></figure>



<p>Not asking is a common issue, especially amongst experienced developers. Programmers are often afraid of asking questions. New guys in a team tend to think that it would be a shame to ask someone for such easy stuff&#8230; But hey, <strong>you&#8217;re new in the team and it&#8217;s perfectly fine to ask for anything that comes to your mind</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>



<p>I&#8217;d say even more &#8211; <strong>by asking questions you show your engagement</strong> and a will to really understand what you&#8217;re doing. Sometimes digging into an issue ourselves can be much longer than doing it with a little bit of help from the project&#8217;s seniors. So <strong>by asking them to aim you in the right direction you&#8217;re also saving yours and your company&#8217;s time</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;" /></p>



<p>When working as a team leader I preferred to have people in my team who asked questions to silent on-my-own geeks. Of course, you should first try to find the solution yourself, e.g. using one of the tips described above <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f44d.png" alt="👍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> However it&#8217;s always better to ask and get the answer or be aimed in the right direction in 5 minutes than spending the whole day fighting with the problem. It would also make your day much better <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">Summary</h2>



<p>I hope these few tips will be useful for you <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>Don&#8217;t be afraid of an unknown codebase. Don&#8217;t try to know it all straight away &#8211; you don&#8217;t need to and even shouldn&#8217;t <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;" /> If the codebase is huge, you&#8217;ll potentially never know it all. Just grasp the main concepts and architecture. Be in touch with your teammates and don&#8217;t be ashamed of asking them questions &#8211; with time, you&#8217;ll ask less <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 think that one of the factors showing a developer&#8217;s experience or <em>seniority</em> is the ability to work with code he/she doesn&#8217;t know. Very often to fix a bug you need to change a single line of code. The trick is to find that line <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>I&#8217;m very curious what are your techniques for approaching an unknown codebase?</strong> <strong>Do you have some tricks to quickly find yourself in legacy code you don&#8217;t know? Share your tips with us in the comments!</strong></p>
<p>The post <a href="https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/">How to Start Working with an Unknown Codebase?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/how-to-start-working-with-an-unknown-codebase/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3584</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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/InterfaceMemberNotImplemented-1.png?fit=300%2C133&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/DiamondOfDeath-1.jpg?fit=300%2C124&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

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


    </div>

  </div>
</div>

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

</div></figure>



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



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


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


<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="1016" height="486" data-attachment-id="3460" data-permalink="https://www.codejourney.net/csharp-8-slicing-indexes-ranges/indexstruct/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?fit=1016%2C486&amp;ssl=1" data-orig-size="1016,486" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="IndexStruct" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexStruct.png?fit=300%2C144&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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">  <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-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">  <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-s><span class=pl-s>$</span>&quot;<span class=pl-kos>{</span><span class=pl-s1>array</span><span class=pl-kos>[</span><span class=pl-c1>^</span><span class=pl-c1>3</span><span class=pl-kos>]</span><span class=pl-kos>}</span>&quot;</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// prints &quot;F&quot; (3rd element from the end)</span></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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/IndexCtorSyntacticSugerHat.png?fit=300%2C137&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeUsingIndexes.png?fit=300%2C142&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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">  <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-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">  <span class=pl-smi>Range</span> <span class=pl-s1>r</span> <span class=pl-c1>=</span> <span class=pl-s1>Range</span><span class=pl-kos>.</span><span class=pl-en>Create</span><span class=pl-kos>(</span><span class=pl-c1>2</span><span class=pl-kos>,</span> <span class=pl-c1>^</span><span class=pl-c1>1</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// range from 2nd to </span></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">                                 <span class=pl-c>// 1st element from the end</span></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">  <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>array</span><span class=pl-kos>[</span><span class=pl-s1>r</span><span class=pl-kos>]</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// prints &quot;CDEFG&quot;</span></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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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">  <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-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">  <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>array</span><span class=pl-kos>[</span><span class=pl-c1>2</span>..<span class=pl-c1>^</span><span class=pl-c1>1</span><span class=pl-kos>]</span><span class=pl-kos>)</span><span class=pl-kos>;</span> <span class=pl-c>// prints &quot;CDEFG&quot;</span></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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/RangeArrayILCSharp.png?fit=236%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg>
</span></template>

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


    </div>

  </div>
</div>

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


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


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

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

  <template class="js-file-alert-template">
  <div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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">  <span class=pl-k>var</span> <span class=pl-s1>devs</span> <span class=pl-c1>=</span> <span class=pl-k>new</span> <span class=pl-smi>Developer</span><span class=pl-kos>[</span><span class=pl-kos>]</span></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">        <span class=pl-kos>{</span></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">            <span class=pl-k>new</span> <span class=pl-smi>Developer</span><span class=pl-kos>(</span><span class=pl-s>&quot;Dawid&quot;</span><span class=pl-kos>)</span><span class=pl-kos>,</span></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">            <span class=pl-k>new</span> <span class=pl-smi>Developer</span><span class=pl-kos>(</span><span class=pl-s>&quot;Mark&quot;</span><span class=pl-kos>)</span><span class=pl-kos>,</span></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">            <span class=pl-k>new</span> <span class=pl-smi>Developer</span><span class=pl-kos>(</span><span class=pl-s>&quot;John&quot;</span><span class=pl-kos>)</span><span class=pl-kos>,</span></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">            <span class=pl-k>new</span> <span class=pl-smi>Developer</span><span class=pl-kos>(</span><span class=pl-s>&quot;Alice&quot;</span><span class=pl-kos>)</span><span class=pl-kos>,</span></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">            <span class=pl-k>new</span> <span class=pl-smi>Developer</span><span class=pl-kos>(</span><span class=pl-s>&quot;Kate&quot;</span><span class=pl-kos>)</span></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">        <span class=pl-kos>}</span><span class=pl-kos>;</span></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">  <span class=pl-k>foreach</span> <span class=pl-kos>(</span><span class=pl-k>var</span> <span class=pl-s1>dev</span> <span class=pl-k>in</span> <span class=pl-s1>devs</span><span class=pl-kos>[</span><span class=pl-c1>1</span>..<span class=pl-c1>^</span><span class=pl-c1>2</span><span class=pl-kos>]</span><span class=pl-kos>)</span> <span class=pl-c>// prints &quot;MarkJohn&quot;</span></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">  <span class=pl-kos>{</span></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">      <span class=pl-s1>Console</span><span class=pl-kos>.</span><span class=pl-en>Write</span><span class=pl-kos>(</span><span class=pl-s1>dev</span><span class=pl-kos>.</span><span class=pl-s1>FirstName</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">  <span class=pl-kos>}</span></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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullRefCode.png?fit=259%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullReferenceException-1.png?fit=300%2C58&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarning.png?fit=300%2C197&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PropertyNotInitializedWarningDisappeared.png?fit=300%2C185&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullAssignationNonnullableString.png?fit=300%2C144&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableReferenceString.png?fit=300%2C209&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/PossibleNullWarning.png?fit=300%2C81&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/CheckingForNull.png?fit=300%2C85&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2019/02/NullableRefTypesIL.png?fit=300%2C112&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/Prototype.png?fit=300%2C99&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_wrapping.png?fit=300%2C86&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/parentheses_end.png?fit=300%2C86&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/11/thanks_javascript.png?fit=265%2C300&amp;ssl=1" 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.10.9 - 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="1767783917" /><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>&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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?fit=275%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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.10.9 - 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="1767783918" /><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>
<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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?fit=284%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?fit=249%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?fit=300%2C43&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?fit=300%2C106&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?fit=300%2C225&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?fit=300%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=136%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?fit=300%2C256&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?fit=300%2C147&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="LOH_manual_compaction.cs">
<tr>
<td id="file-loh_manual_compaction-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-loh_manual_compaction-cs-LC1" class="blob-code blob-code-inner js-file-line">  GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;</td>
</tr>
<tr>
<td id="file-loh_manual_compaction-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-loh_manual_compaction-cs-LC2" class="blob-code blob-code-inner js-file-line">  GC.Collect();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c41faa4201d987b17102f0229dfa20cc/raw/4b9004f1d32a3576ff40271590ed0e3cc82130b2/LOH_manual_compaction.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c41faa4201d987b17102f0229dfa20cc#file-loh_manual_compaction-cs" class="Link--inTextBlock"><br />
          LOH_manual_compaction.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>There might be some niche cases in which LOH compaction may be useful. More details and discussions can be found for example <a href="https://stackoverflow.com/questions/20035550/large-object-heap-compaction-when-is-it-good" target="_blank" rel="noopener">here</a>.</p>
<h2>Best practices working with LOH objects</h2>
<p>We can try to simply design our applications to use the less possible number of large objects, but let&#8217;s not exaggerate. We are living in a world where 8GBs of 2133MHz RAM costs sometimes less than 100$, so the memory is generally cheap <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>In principle, the rule seems to be simple: <strong>large objects we allocate should be reused (e.g. cached) as much as possible</strong>.</p>
<p>We should just keep in mind that allocation of large objects can be costly, because of a need to perform gen 2 collection in some cases before the object is allocated.</p>
<p>An example of potentially problematic large object can be a <a href="https://msdn.microsoft.com/en-us/library/ms972976.aspx" target="_blank" rel="noopener">ViewState</a> used in ASP.NET applications, size of which can easily exceed 85K. There are some good articles explaining how to not stupidly incur ASP.NET app&#8217;s performance using it, for instance <a href="https://dzone.com/articles/optimize-aspnet-performance-with-view-state-cachin" target="_blank" rel="noopener">this one</a>.</p>
<p>There are also a lot of tools which can be used to measure the memory state and performance of our applications (also its internal mechanisms like garbage collection, heaps compaction etc.) which we&#8217;ll surely cover in one of the next posts within <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">the series</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Summary</h1>
<p>Today we examined &#8211; previously a bit forgotten &#8211; Large Object Heap. We saw how the information about free memory blocks on it is stored by .NET Framework and how new objects are allocated on it.</p>
<p>&nbsp;</p>
<p>I think it&#8217;s one of the next internal concepts of .NET worth knowing and understanding, even though in the common scenarios and business applications you probably won&#8217;t get into troubles with LOH. However, it may be practical and useful to know when working with some more memory-demanding applications like games.</p>
<p>I hope this post clarifies some LOH topics for you.</p>
<p><span style="text-decoration: underline;">Let me know if there are any topics you&#8217;d be interested in reading about</span>. I&#8217;m here to provide some value to you, so I&#8217;m open for your criticism and suggestions <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Stay tuned!</p>
<p>&nbsp;</p>
<p><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.10.9 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-7" 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="1767783919" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-7" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/">[.NET Internals 08] What about Large Object Heap (LOH)?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2812</post-id>	</item>
		<item>
		<title>[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</title>
		<link>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/</link>
					<comments>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 05 Sep 2018 13:00:22 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2779</guid>

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

					<description><![CDATA[<p>Continuing .NET Internals series on the blog, today we&#8217;re going to see what is generational garbage collection. You&#8217;ll also get to know what is a card table data structure and for what it&#8217;s used 🙂 Heaps generations As we know from this post, heaps used by .NET process to allocate reference objects are allocated on&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-06-generational-garbage-collection/">[.NET Internals 06] Generational garbage collection</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Continuing .<a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">NET Internals series on the blog</a>, today we&#8217;re going to see what is <em>generational garbage collection</em>. You&#8217;ll also get to know what is a <em>card table</em> data structure and for what it&#8217;s used <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2741"></span></p>
<h1>Heaps generations</h1>
<p>As we know from <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">this post</a>, heaps used by .NET process to allocate reference objects are allocated on different kinds of heaps. In <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">the previous article</a> we also got to know that only Small Object Heap (SOH) is the subject of compaction process. Large Object Heap (LOH) is not compacted because of the performance reasons.</p>
<p>This is however not the only optimization introduced by GC contributors into Small Object Heap. SOH in .NET is also divided into <strong>3 generations</strong>:</p>
<ul>
<li>Generation 0 &#8211; containing newly created objects, which did not have any collection performed on them so far,</li>
<li>Generation 1 &#8211; storing objects that survived a single garbage collection (were not reclaimed during it because of still being in use),</li>
<li>Generation 2 &#8211; keeping long-lived objects that survived two or more GC cycles.</li>
</ul>
<p><span style="font-size: 10pt;">LOH is not divided into generations. More details on LOH management in the article linked just before the &#8220;Summary&#8221; section below.</p>
<p></span></p>
<p>Thanks to such a division of managed heap, the actual collection is performed not on the whole heap, but only on one of the generations, where:</p>
<blockquote>
<p><em>to perform a collection on generation X</em> == to collect objects on generation X and all its younger generations</p>
</blockquote>
<p>That&#8217;s why a <strong>generation 2 collection is knows as a full garbage collection</strong>. During this process objects present on all heaps (on all generations: gen 0, gen 1 and gen 2) are examined and reclaimed. Obviously, this collection is also the most costly one.</p>
<h1>Collection survivors</h1>
<p>In that place we should introduce a term <em>collection survivor</em>. It can be defined as an object which <em>survives</em> the collection (is not collected during GC collection cycle as it&#8217;s still referenced by something).</p>
<p>Knowing that, the following &#8220;promotion rules&#8221; can be defined:</p>
<ul>
<li>object <strong>survives</strong> <strong>generation 0</strong> collection =&gt; object is <strong>promoted to generation 1</strong>,</li>
<li>object <strong>survives generation 1</strong> collection =&gt; object is <strong>promoted to generation 2</strong>,</li>
<li>object <strong>survives generation 2</strong> collection =&gt; object <strong>stays in generation 2</strong>.</li>
</ul>
<h1>Collection thresholds in generations</h1>
<p>In the <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">5th post in the series</a>, it was mentioned that one of the conditions on which the garbage collection can be triggered is when &#8220;the memory used by the objects on the managed heap exceeds some defined threshold&#8221;. In fact, this is not a single threshold, but several thresholds. More precisely, there&#8217;s a separate one per generation. As soon as size of all objects in a particular generation exceeds threshold&#8217;s value, the collection is started.</p>
<p>In the beginning, the thresholds&#8217; values for each generation are initialized to the following values:</p>
<ul>
<li>gen 0: ~256K,</li>
<li>gen 1: ~2MBs,</li>
<li>gen 2: ~10MBs.</li>
</ul>
<p>Nonetheless, these are only <strong>initial</strong> values and are adjusted by the GC at runtime. One of the conditions to increase a particular threshold&#8217;s value is then the survival rate in a generation is high (more objects from particular generation are either promoted to the next one or stay in generation 2), which makes the GC cycles to run less frequently (the condition of exceeding the threshold is not met that often).</p>
<p>This approach seems reasonable, as the main goal of GC is to collect as many objects as possible and reclaim their memory, not to &#8220;waste time&#8221; only to get to know that most of the objects are still in use.</p>
<p>In general, CLR tries to find a balance between two factors:</p>
<ul>
<li>not letting application&#8217;s working memory set to get too big,</li>
<li>not allowing GC to take too much time.</li>
</ul>
<h1>Structure of generational heap</h1>
<p>The diagram below presents how SOH actually looks like being divided into above-described 3 generations:</p>
<p><figure id="attachment_2747" aria-describedby="caption-attachment-2747" style="width: 640px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2747" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/soh_generations/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?fit=640%2C399&amp;ssl=1" data-orig-size="640,399" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="SOH_Generations" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?fit=300%2C187&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?fit=300%2C116&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?fit=300%2C195&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?fit=300%2C104&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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.10.9 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-9" 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="1767783924" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-9" /><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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?fit=300%2C246&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?fit=300%2C242&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?fit=300%2C177&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?fit=300%2C206&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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"><span class=pl-smi>int</span> <span class=pl-s1>i</span> <span class=pl-c1>=</span> <span class=pl-c1>123</span><span class=pl-kos>;</span></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"><span class=pl-c>// Boxing &#8211; copying the value of i into object o.</span></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"><span class=pl-smi>object</span> <span class=pl-s1>o</span> <span class=pl-c1>=</span> <span class=pl-s1>i</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/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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?fit=228%2C148&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?fit=228%2C215&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?fit=300%2C266&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?fit=300%2C77&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?fit=300%2C41&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?fit=300%2C127&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?fit=300%2C132&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?fit=300%2C41&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?fit=300%2C216&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?fit=300%2C245&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?fit=300%2C195&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?fit=300%2C148&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?fit=300%2C134&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?fit=300%2C161&amp;ssl=1" 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.10.9 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-10" 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="1767783928" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-10" /><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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?fit=300%2C264&amp;ssl=1" 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-medium-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-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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?fit=207%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?fit=300%2C274&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=136%2C300&amp;ssl=1" 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.10.9 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-11" 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="1767783928" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-11" /><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>T-SQL/SSMS: transaction rollback in scripts with XACT_ABORT ON, GO statements and syntax errors</title>
		<link>https://www.codejourney.net/t-sqlssms-transaction-rollback-in-scripts-with-xact_abort-on-go-statements-and-syntax-errors/</link>
					<comments>https://www.codejourney.net/t-sqlssms-transaction-rollback-in-scripts-with-xact_abort-on-go-statements-and-syntax-errors/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 16 Nov 2017 07:00:40 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[T-SQL]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2425</guid>

					<description><![CDATA[<p>I&#8217;ve recently met a weird issue with T-SQL scripts at work and would like to share it with you today 🙂 T-SQL script with multiple objects created On daily basis I work a lot with MS SQL Server databases. We often create many T-SQL objects (tables, views, procedures, functions) and because of some reasons we&#8230;</p>
<p>The post <a href="https://www.codejourney.net/t-sqlssms-transaction-rollback-in-scripts-with-xact_abort-on-go-statements-and-syntax-errors/">T-SQL/SSMS: transaction rollback in scripts with XACT_ABORT ON, GO statements and syntax errors</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve recently met a weird issue with T-SQL scripts at work and would like to share it with you 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;" /><br />
<span id="more-2425"></span></p>
<h1>T-SQL script with multiple objects created</h1>
<p>On daily basis I work a lot with MS SQL Server databases. We often create many T-SQL objects (tables, views, procedures, functions) and because of some reasons we cannot use Entity Framework or another from widely available ORMs. Nonetheless, all objects created in the database must be kept in the form of SQL scripts (files) containing set of <em>CREATE</em>, <em>ALTER</em>, <em>INSERT</em>, <em>DELETE</em> or whatever T-SQL statements.</p>
<p>What we often do is to create a single <em>.sql</em> file, which in fact often contains more than one, separate (independent) SQL statements (e.g. creates a table and a procedure). What we obviously want to ensure is that when executing the script either all statements are committed to the database or none of them. This means that if in a part responsible for creating a particular object any SQL error is raised, execution of the whole script should be interrupted and the whole transaction rolled back, so in effect none of the objects contained within this script are created (none of the statements batches is committed). Here the issue comes out.</p>
<h1><span title="Hint: double-click to select code">SQL script with XACT_ABORT</span><span title="Hint: double-click to select code"> </span><span title="Hint: double-click to select code">ON and GO statements</span></h1>
<p>In order to handle above-described requirements, the template for SQL script looks as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83104201" 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-sql_template-sql" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-tsql  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="SQL_template.sql content, created by dsibinski on 08:32PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="SQL_template.sql">
<tr>
<td id="file-sql_template-sql-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-sql_template-sql-LC1" class="blob-code blob-code-inner js-file-line">  SET XACT_ABORT ON</td>
</tr>
<tr>
<td id="file-sql_template-sql-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-sql_template-sql-LC2" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
<tr>
<td id="file-sql_template-sql-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-sql_template-sql-LC3" class="blob-code blob-code-inner js-file-line">  BEGIN TRANSACTION</td>
</tr>
<tr>
<td id="file-sql_template-sql-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-sql_template-sql-LC4" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
<tr>
<td id="file-sql_template-sql-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-sql_template-sql-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-sql_template-sql-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-sql_template-sql-LC6" class="blob-code blob-code-inner js-file-line">  &#8212; SQL object 1 (CREATE/ALTER/INSERT etc&#8230;)</td>
</tr>
<tr>
<td id="file-sql_template-sql-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-sql_template-sql-LC7" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
<tr>
<td id="file-sql_template-sql-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-sql_template-sql-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-sql_template-sql-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-sql_template-sql-LC9" class="blob-code blob-code-inner js-file-line">  &#8212; SQL object 2 (CREATE/ALTER/INSERT etc&#8230;)</td>
</tr>
<tr>
<td id="file-sql_template-sql-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-sql_template-sql-LC10" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
<tr>
<td id="file-sql_template-sql-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-sql_template-sql-LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-sql_template-sql-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-sql_template-sql-LC12" class="blob-code blob-code-inner js-file-line">  &#8212; next SQL batches if needed, each followed by GO</td>
</tr>
<tr>
<td id="file-sql_template-sql-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-sql_template-sql-LC13" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-sql_template-sql-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-sql_template-sql-LC14" class="blob-code blob-code-inner js-file-line">  COMMIT</td>
</tr>
<tr>
<td id="file-sql_template-sql-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-sql_template-sql-LC15" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/39e47705e1d6d5f16c7a45badab543c8/raw/e6739f6192abc2e6b3b9226f01de3ee1e622f058/SQL_template.sql" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/39e47705e1d6d5f16c7a45badab543c8#file-sql_template-sql" class="Link--inTextBlock"><br />
          SQL_template.sql<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Firstly, we set <em>XACT_ABORT</em> to <em><span class="pl-k">ON. </span></em><span class="pl-k">This setting, <a href="https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql" target="_blank" rel="noopener">according to Microsoft docs</a>, &#8220;specifies whether SQL Server automatically rolls back the current transaction when a Transact-SQL statement raises a run-time error&#8221;. That&#8217;s what we want &#8211; in case of any errors the whole opened transaction should be rolled back.</p>
<p></span></p>
<p>Then we open a transaction with <em>BEGIN TRANSACTION, </em>which is committed to the server at the end of the script with <em>COMMIT</em> statement.</p>
<p>In between, we put the actual SQL statements that are responsible for creating new SQL objects or sometimes executing some procedure, inserting some data etc.</p>
<p>As can be noticed, each of these SQL &#8220;chunks&#8221; is followed by a <em>GO</em> statement. <em>GO</em> is one of the SQL Server statements, that are not T-SQL statements, but are recognized by the <strong class="">sqlcmd</strong> utility and SQL Server Management Studio (SSMS). <em>GO</em> statement allows to separate a script into <em>batches</em>. When <em>GO</em> is used, it signals the end of a batch and sends it to the SQL Server. It is necessary in order to separate T-SQL statements (e.g. to separate a procedure&#8217;s creation part from another procedure&#8217;s <em>EXEC</em> statement coming just after). That is also what comes in default in scripts generated by SSMS.</p>
<p>Of course, everything is in one, big transaction, so everything will be ok, right? When there is any error in any of the batches all other statements will be rolled back? Not necessarily!</p>
<h1><span title="Hint: double-click to select code">XACT_ABORT</span><span title="Hint: double-click to select code"> </span><span title="Hint: double-click to select code">ON and syntax errors</span></h1>
<p>If we take a closer look at the above-cited description of <em>XACT_ABORT</em> from the Microsoft docs, it says that with this setting set to <em>ON</em>, transaction is rolled back &#8220;<span class="pl-k">when a Transact-SQL statement raises a <strong>run-time error</strong>&#8220;. <strong>Bold</strong> part is crucial here &#8211; it only works for <strong>run-time</strong> errors.</p>
<p></span></p>
<p>Let&#8217;s consider the following sample .sql script:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83104663" 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-peopletable_proc_exec-sql" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-tsql  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="PeopleTable_proc_exec.sql content, created by dsibinski on 08:48PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="PeopleTable_proc_exec.sql">
<tr>
<td id="file-peopletable_proc_exec-sql-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-peopletable_proc_exec-sql-LC1" class="blob-code blob-code-inner js-file-line">   SET xact_abort ON </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-peopletable_proc_exec-sql-LC2" class="blob-code blob-code-inner js-file-line">   GO </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-peopletable_proc_exec-sql-LC3" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-peopletable_proc_exec-sql-LC4" class="blob-code blob-code-inner js-file-line">   BEGIN TRANSACTION </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-peopletable_proc_exec-sql-LC5" class="blob-code blob-code-inner js-file-line">   GO </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-peopletable_proc_exec-sql-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-peopletable_proc_exec-sql-LC7" class="blob-code blob-code-inner js-file-line">   CREATE TABLE [dbo].[People] </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-peopletable_proc_exec-sql-LC8" class="blob-code blob-code-inner js-file-line">     ( </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-peopletable_proc_exec-sql-LC9" class="blob-code blob-code-inner js-file-line">        [id]        [INT] IDENTITY(1, 1) NOT NULL, </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-peopletable_proc_exec-sql-LC10" class="blob-code blob-code-inner js-file-line">        [name]      [NVARCHAR](max) NOT NULL, </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-peopletable_proc_exec-sql-LC11" class="blob-code blob-code-inner js-file-line">        [timestamp] [TIMESTAMP] NOT NULL, </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-peopletable_proc_exec-sql-LC12" class="blob-code blob-code-inner js-file-line">        CONSTRAINT [PK_People] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (pad_index = </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-peopletable_proc_exec-sql-LC13" class="blob-code blob-code-inner js-file-line">        OFF, statistics_norecompute = OFF, ignore_dup_key = OFF, allow_row_locks = </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-peopletable_proc_exec-sql-LC14" class="blob-code blob-code-inner js-file-line">        on, allow_page_locks = on) ON [PRIMARY] </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-peopletable_proc_exec-sql-LC15" class="blob-code blob-code-inner js-file-line">     ) </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-peopletable_proc_exec-sql-LC16" class="blob-code blob-code-inner js-file-line">   ON [PRIMARY] </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-peopletable_proc_exec-sql-LC17" class="blob-code blob-code-inner js-file-line">   textimage_on [PRIMARY] </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-peopletable_proc_exec-sql-LC18" class="blob-code blob-code-inner js-file-line">   GO </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-peopletable_proc_exec-sql-LC19" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-peopletable_proc_exec-sql-LC20" class="blob-code blob-code-inner js-file-line">   CREATE PROCEDURE [dbo].[InsertPerson] @name NVARCHAR(max) </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-peopletable_proc_exec-sql-LC21" class="blob-code blob-code-inner js-file-line">   AS </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-peopletable_proc_exec-sql-LC22" class="blob-code blob-code-inner js-file-line">     BEGIN </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-peopletable_proc_exec-sql-LC23" class="blob-code blob-code-inner js-file-line">         INSERT INTO dbo.People </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-peopletable_proc_exec-sql-LC24" class="blob-code blob-code-inner js-file-line">                     (NAME) </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-peopletable_proc_exec-sql-LC25" class="blob-code blob-code-inner js-file-line">         VALUES      (@name); </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-peopletable_proc_exec-sql-LC26" class="blob-code blob-code-inner js-file-line">     END </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-peopletable_proc_exec-sql-LC27" class="blob-code blob-code-inner js-file-line">   GO </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-peopletable_proc_exec-sql-LC28" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
<td id="file-peopletable_proc_exec-sql-LC29" class="blob-code blob-code-inner js-file-line">   INSERT INTO dbo.Persons &#8212; run-time error &#8211; dbo.Persons table does not exist</td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
<td id="file-peopletable_proc_exec-sql-LC30" class="blob-code blob-code-inner js-file-line">               (NAME) </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
<td id="file-peopletable_proc_exec-sql-LC31" class="blob-code blob-code-inner js-file-line">   VALUES      (&#39;Dawid&#39;) </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
<td id="file-peopletable_proc_exec-sql-LC32" class="blob-code blob-code-inner js-file-line">   GO </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
<td id="file-peopletable_proc_exec-sql-LC33" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
<td id="file-peopletable_proc_exec-sql-LC34" class="blob-code blob-code-inner js-file-line">   COMMIT </td>
</tr>
<tr>
<td id="file-peopletable_proc_exec-sql-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
<td id="file-peopletable_proc_exec-sql-LC35" class="blob-code blob-code-inner js-file-line">   GO  </td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/b265d5a9494407df6049d5decb3c02b6/raw/61c87d8c591b9dbd3dd73daabbed70caae518f4e/PeopleTable_proc_exec.sql" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/b265d5a9494407df6049d5decb3c02b6#file-peopletable_proc_exec-sql" class="Link--inTextBlock"><br />
          PeopleTable_proc_exec.sql<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Here we have 3 T-SQL batches:</p>
<ul>
<li>Lines 7-17 contain a table&#8217;s creation statement</li>
<li>Lines 20-26 contain a procedure&#8217;s creation statement</li>
<li>Lines 29-31 contains an <em>INSERT</em> statement.
</li>
</ul>
<p>The last batch contains run-time error &#8211; there is no table <em>dbo.Persons </em>in the db. Execution of the above script in SSMS returns the following error:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83107118" 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-tsql_runtime_error-log" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-text  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="TSQL_runtime_error.log content, created by dsibinski on 10:06PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="TSQL_runtime_error.log">
<tr>
<td id="file-tsql_runtime_error-log-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-tsql_runtime_error-log-LC1" class="blob-code blob-code-inner js-file-line">  Msg 208, Level 16, State 1, Line 33</td>
</tr>
<tr>
<td id="file-tsql_runtime_error-log-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-tsql_runtime_error-log-LC2" class="blob-code blob-code-inner js-file-line">  Invalid object name &#39;dbo.Persons&#39;.</td>
</tr>
<tr>
<td id="file-tsql_runtime_error-log-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-tsql_runtime_error-log-LC3" class="blob-code blob-code-inner js-file-line">  Msg 3902, Level 16, State 1, Line 39</td>
</tr>
<tr>
<td id="file-tsql_runtime_error-log-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-tsql_runtime_error-log-LC4" class="blob-code blob-code-inner js-file-line">  The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/3f22670393358554f4847fc6523bf947/raw/5a80154af2055976e92ce58440256199845bddb7/TSQL_runtime_error.log" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/3f22670393358554f4847fc6523bf947#file-tsql_runtime_error-log" class="Link--inTextBlock"><br />
          TSQL_runtime_error.log<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>What we expect to happen is that because the last batch produced run-time error, the table and the procedure will not be created. <strong>And exactly this happens &#8211; neither the table nor the procedure is created in the database</strong>. <em>SET XACT_ABORT ON </em>did its job. Uff.</p>
<p>Now, let&#8217;s modify the last, <em>INSERT</em> statement by introducing a <strong>syntax error</strong> so it looks as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83105125" 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-insert_with_syntax_error-sql" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-sql  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Insert_with_syntax_error.sql content, created by dsibinski on 09:03PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="Insert_with_syntax_error.sql">
<tr>
<td id="file-insert_with_syntax_error-sql-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-insert_with_syntax_error-sql-LC1" class="blob-code blob-code-inner js-file-line">   INssSERT INTO dbo.Persons &#8212; syntax error &#8211; &#39;INssSERT&#39; instead of &#39;INSERT&#39;</td>
</tr>
<tr>
<td id="file-insert_with_syntax_error-sql-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-insert_with_syntax_error-sql-LC2" class="blob-code blob-code-inner js-file-line">               (NAME) </td>
</tr>
<tr>
<td id="file-insert_with_syntax_error-sql-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-insert_with_syntax_error-sql-LC3" class="blob-code blob-code-inner js-file-line">   VALUES      (&#39;Dawid&#39;) </td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/476478318a479a951f29b7f1f59af7da/raw/df392d86b509895d5a4cb16d83a1268b03edd2e7/Insert_with_syntax_error.sql" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/476478318a479a951f29b7f1f59af7da#file-insert_with_syntax_error-sql" class="Link--inTextBlock"><br />
          Insert_with_syntax_error.sql<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Full .sql script with this change <a href="https://gist.github.com/dsibinski/aa95f17a96d704a499123816c1dc42a0" target="_blank" rel="noopener">is available here</a>.</p>
<p>Does it change a lot? We will still get an error during the script&#8217;s execution, right? Yes &#8211; we will get the following error:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83107142" 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-tsql_syntax_error-log" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-text  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="TSQL_syntax_error.log content, created by dsibinski on 10:06PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="TSQL_syntax_error.log">
<tr>
<td id="file-tsql_syntax_error-log-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-tsql_syntax_error-log-LC1" class="blob-code blob-code-inner js-file-line">   Msg 156, Level 15, State 1, Line 29</td>
</tr>
<tr>
<td id="file-tsql_syntax_error-log-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-tsql_syntax_error-log-LC2" class="blob-code blob-code-inner js-file-line">   Incorrect syntax near the keyword &#39;INTO&#39;.</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/42cc11d46141969b5530a03ab22a5c42/raw/cf9b38c9bb8f4b590ad7fc8be3eeaeef331baaf0/TSQL_syntax_error.log" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/42cc11d46141969b5530a03ab22a5c42#file-tsql_syntax_error-log" class="Link--inTextBlock"><br />
          TSQL_syntax_error.log<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>However, surprisingly, the table and the procedure <strong>are well-created in the database</strong>! The following screenshot presents:</p>
<p><figure id="attachment_2430" aria-describedby="caption-attachment-2430" style="width: 560px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2430" data-permalink="https://www.codejourney.net/t-sqlssms-transaction-rollback-in-scripts-with-xact_abort-on-go-statements-and-syntax-errors/ssms_objectscreated/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?fit=831%2C377&amp;ssl=1" data-orig-size="831,377" 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="SSMS_ObjectsCreated" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?fit=300%2C136&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?fit=831%2C377&amp;ssl=1" class="wp-image-2430" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?resize=560%2C254&#038;ssl=1" alt="" width="560" height="254" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?w=831&amp;ssl=1 831w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?resize=300%2C136&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?resize=768%2C348&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/11/SSMS_ObjectsCreated.png?resize=720%2C327&amp;ssl=1 720w" sizes="auto, (max-width: 560px) 100vw, 560px" /></a><figcaption id="caption-attachment-2430" class="wp-caption-text">Objects created despite an error</figcaption></figure></p>
<p>Why did it happen? Why <em>XACT_ABORT</em> set to <em>ON</em> the whole transaction was <strong>not rolled back</strong>? That&#8217;s because, after re-reading again-mentioned <a href="https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql" target="_blank" rel="noopener">Microsoft docs</a>, &#8220;compile errors, such as <strong>syntax errors, are not affected by SET XACT_ABORT</strong>&#8220;. Huh!</p>
<h1>Solution</h1>
<p>The only solution to this issue I found so far is to check, after each <em>GO</em> statement, if any errors occurred (using <span title="Hint: double-click to select code"><em>@@error</em>) and if yes, interrupt the whole script&#8217;s execution using <a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql" target="_blank" rel="noopener"><em>raiserror</em></a>, for instance:</span></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83105562" 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-go_raiserrror_usage-sql" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-tsql  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="GO_raiserrror_usage.sql content, created by dsibinski on 09:16PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="GO_raiserrror_usage.sql">
<tr>
<td id="file-go_raiserrror_usage-sql-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-go_raiserrror_usage-sql-LC1" class="blob-code blob-code-inner js-file-line">  INssSERT INTO dbo.Persons (NAME) VALUES (&#39;Dawid&#39;) </td>
</tr>
<tr>
<td id="file-go_raiserrror_usage-sql-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-go_raiserrror_usage-sql-LC2" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
<tr>
<td id="file-go_raiserrror_usage-sql-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-go_raiserrror_usage-sql-LC3" class="blob-code blob-code-inner js-file-line">  if @@error != 0 raiserror(&#39;Error in script execution&#39;, 20, -1) with log</td>
</tr>
<tr>
<td id="file-go_raiserrror_usage-sql-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-go_raiserrror_usage-sql-LC4" class="blob-code blob-code-inner js-file-line">  GO</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/f8a9a5dea9606db4a953d7e3f04dba7c/raw/9d645072f524162468619ece5a32af53fd92dd00/GO_raiserrror_usage.sql" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/f8a9a5dea9606db4a953d7e3f04dba7c#file-go_raiserrror_usage-sql" class="Link--inTextBlock"><br />
          GO_raiserrror_usage.sql<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><!-- Invalid Gist ID --></p>
<p>After introducing this solution to our example script, it looks <a href="https://gist.github.com/dsibinski/f08e5e685a620246b6d528fcba4ad3ff" target="_blank" rel="noopener">as in this gist</a>. After executing it in SSMS, the error is a bit different:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist83107195" 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-tsql_raiseerror-log" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-text  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="TSQL_raiseerror.log content, created by dsibinski on 10:08PM on November 15, 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="TSQL_raiseerror.log">
<tr>
<td id="file-tsql_raiseerror-log-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-tsql_raiseerror-log-LC1" class="blob-code blob-code-inner js-file-line">  Msg 156, Level 15, State 1, Line 33</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-tsql_raiseerror-log-LC2" class="blob-code blob-code-inner js-file-line">  Incorrect syntax near the keyword &#39;INTO&#39;.</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-tsql_raiseerror-log-LC3" class="blob-code blob-code-inner js-file-line">  Msg 2745, Level 16, State 2, Line 37</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-tsql_raiseerror-log-LC4" class="blob-code blob-code-inner js-file-line">  Process ID 53 has raised user error 50000, severity 20. SQL Server is terminating this process.</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-tsql_raiseerror-log-LC5" class="blob-code blob-code-inner js-file-line">  Msg 50000, Level 20, State 1, Line 37</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-tsql_raiseerror-log-LC6" class="blob-code blob-code-inner js-file-line">  Error in script execution</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-tsql_raiseerror-log-LC7" class="blob-code blob-code-inner js-file-line">  Msg 596, Level 21, State 1, Line 36</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-tsql_raiseerror-log-LC8" class="blob-code blob-code-inner js-file-line">  Cannot continue the execution because the session is in the kill state.</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-tsql_raiseerror-log-LC9" class="blob-code blob-code-inner js-file-line">  Msg 0, Level 20, State 0, Line 36</td>
</tr>
<tr>
<td id="file-tsql_raiseerror-log-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-tsql_raiseerror-log-LC10" class="blob-code blob-code-inner js-file-line">  A severe error occurred on the current command. The results, if any, should be discarded.</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7144531626859183d598f83fa772f3f4/raw/de27605afd2dfb5a438e7e65910308aa75cb20b9/TSQL_raiseerror.log" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7144531626859183d598f83fa772f3f4#file-tsql_raiseerror-log" class="Link--inTextBlock"><br />
          TSQL_raiseerror.log<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and <strong>neither the table nor the procedure is created in the database</strong>. That&#8217;s what we need.</p>
<h1>Summary</h1>
<p>I found this issue confusing and weird, especially that I could not find any equivalent to <em>XACT_ABORT</em> which would satisfy my needs and affect also syntax errors. The solution with checking for errors after each <em>GO</em> statement works fine, but is far from perfect.</p>
<p><span style="text-decoration: underline;"><strong>Maybe you have some more experience in this topic and know any better solution? It&#8217;d be appreciated!</strong></span></p>
<p>&nbsp;</p>
<p>The post <a href="https://www.codejourney.net/t-sqlssms-transaction-rollback-in-scripts-with-xact_abort-on-go-statements-and-syntax-errors/">T-SQL/SSMS: transaction rollback in scripts with XACT_ABORT ON, GO statements and syntax errors</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/t-sqlssms-transaction-rollback-in-scripts-with-xact_abort-on-go-statements-and-syntax-errors/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2425</post-id>	</item>
		<item>
		<title>Xamarin.Android &#8211; ASP.NET web api synchronization &#8211; research</title>
		<link>https://www.codejourney.net/xamarin-android-asp-net-web-api-synchronization-research/</link>
					<comments>https://www.codejourney.net/xamarin-android-asp-net-web-api-synchronization-research/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 27 Sep 2017 06:00:45 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[asp-net-core]]></category>
		<category><![CDATA[moneyback]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2345</guid>

					<description><![CDATA[<p>As you may know, in my MoneyBack Xamarin.Android application I&#8217;ve used SQLite as the local db management system. Recently I&#8217;ve added an ASP.NET Core web solution to my GitHub repository in order to create back-end API for my mobile app. I wanted to have database hosted on a remote server and Android application to synchronize its data&#8230;</p>
<p>The post <a href="https://www.codejourney.net/xamarin-android-asp-net-web-api-synchronization-research/">Xamarin.Android &#8211; ASP.NET web api synchronization &#8211; research</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As you may know, in my <a href="https://github.com/dsibinski/MoneyBack" target="_blank" rel="noopener noreferrer">MoneyBack</a> Xamarin.Android application I&#8217;ve used <a href="https://www.codejourney.net/2017/03/using-sqlite-database-in-xamarin-android/" target="_blank" rel="noopener noreferrer">SQLite</a> as the local db management system. Recently I&#8217;ve added an <a href="https://github.com/dsibinski/MoneyBack.Web" target="_blank" rel="noopener noreferrer">ASP.NET Core web solution to my GitHub repository</a> in order to create back-end API for my mobile app. I wanted to have database hosted on a remote server and Android application to synchronize its data with it.<br />
Then I started wondering&#8230; and decided to make a deeper research first. As I wrote in <a href="https://www.codejourney.net/2017/05/dajsiepoznac2017-summary/" target="_blank" rel="noopener noreferrer">my post summing up DajSiePoznac2017 competition</a>, &#8220;before using a particular solution for an issue&#8221; we should &#8220;better examine the other possibilities&#8221; first. So I do <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-2345"></span></p>
<h2>Why to synchronize with remote database?</h2>
<p>First question to ask is <strong>why to synchronize with a remote database at all</strong>?</p>
<h6>There are a few obvious advantages:</h6>
</p>
<p><strong>(+)</strong> users&#8217; data is stored &#8220;in a cloud&#8221; and can be accessed from any device</p>
<p><strong>(+)</strong> users don&#8217;t need to worry about backing-up their data</p>
<p><strong>(+)</strong> data storage logic is moved to the web part of the system and with API exposed it can be easier to port it to other platforms</p>
<p><strong>(+)</strong> having web API, a web client can be easily added to the system.</p>
<h6>However, there are also some harms:</h6>
<p><strong>(-)</strong> synchronization of local and remote data (online and offline) must be handled</p>
<p><strong>(-)</strong> synchronization uses some network data and battery of a mobile device</p>
<p><strong>(-) </strong>web API must be maintained and after each change in it mobile app must be adjusted.</p>
<p>Despite all these aspects I&#8217;ve been wondering to implement a web API for few different reasons. First of all this could be a great programming experience, very interesting from architectural point of view. Secondly, I think this is a bit old-fashioned and messy that a user needs to export some database/app files backup to his GDrive in order to not lose his data.</p>
<p>Frankly, I just want to have some fun with ASP.NET Core, implement a web API and make <a href="https://github.com/dsibinski/MoneyBack" target="_blank" rel="noopener noreferrer">MoneyBack</a> working with 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;" /> Maybe some Linux deployment after all? Let&#8217;s create some nice programming playground <a href="https://github.com/dsibinski/MoneyBack/tree/master/Web" target="_blank" rel="noopener noreferrer">here</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>
<h2>How to synchronize with web API?</h2>
<p>That&#8217;s the question I&#8217;ve been searching an answer for recently. Long story short, the idea is to have a <strong>back-end database management system hosted on a web server</strong> and mobile app having its own local &#8220;mirror&#8221; of the database, <strong>bidirectionally synchronizing local data with remote database through web API</strong>. Mobile app should work in <strong>offline-first</strong> mode, which means that all operations must be possible to be done locally and potential (not mandatory) synchronization to happen as soon as it&#8217;s possible (user is connected to WiFi, has mobile network access etc.)</p>
<p>There are various possibilities and solutions to handle synchronization of mobile app&#8217;s data and remote database storage, from synchronization system built from scratch to Azure cloud hosting.</p>
<h4>Custom synchronization mechanism</h4>
<p>We could of course implement our own data synchronization mechanism. There are many tutorials available, including for instance <a href="https://xamarinhelp.com/mobile-database-bi-directional-synchronization-rest-api/" target="_blank" rel="noopener noreferrer">this one</a>, which describes all the contents quite nicely and I recommend reading it even if you don&#8217;t want to implement sync on your own &#8211; it helps understanding all the concepts.</p>
<p>Custom synchronization can be a lot of fun, but&#8230; why to reinvent the wheel?</p>
<h4>Azure Mobile App Service</h4>
<p><a href="https://azure.microsoft.com/en-us/services/app-service/mobile/" target="_blank" rel="noopener noreferrer">Microsoft&#8217;s Azure Mobile App Service</a> is recommended almost everywhere &#8211; <a href="https://stackoverflow.com/questions/33224792/using-xamarin-android-i-want-to-sync-sqlite-with-sql-server" target="_blank" rel="noopener noreferrer">on StackOverflow</a>, in the official <a href="https://developer.xamarin.com/guides/xamarin-forms/cloud-services/sync/" target="_blank" rel="noopener noreferrer">Xamarin documentation</a> and on a lot of blogs, but its free plan seems to not be worth using (except of performing some simple tests) while paid plans are more <em>enterprisy</em>. It seems great, but for my playground I neither want to pay nor use free plan which may become unusable after re-implementing the whole back-end.</p>
<h4>Realm.io</h4>
<p>Finally, out of a sudden, I found it. <a href="https://realm.io/docs/get-started/overview/" target="_blank" rel="noopener noreferrer">Realm.io</a> is a totally separate database system built especially for mobile solutions. Its <a href="https://realm.io/products/realm-mobile-database/" target="_blank" rel="noopener noreferrer">Mobile Database</a> may be used as the db framework for a mobile app (<a href="https://realm.io/docs/xamarin/latest/" target="_blank" rel="noopener noreferrer">Xamarin is also supported</a>), replacing for instance <a href="https://www.codejourney.net/2017/03/using-sqlite-database-in-xamarin-android/" target="_blank" rel="noopener noreferrer">SQLite</a>. After all, <a href="https://realm.io/products/realm-mobile-platform/" target="_blank" rel="noopener noreferrer">Realm Mobile Platform</a> can be used on a server-side handling mobile/web APIs and data synchronization &#8211; documentation says it supports .NET Core 1.1. Let&#8217;s hope they add support for 2.0 soon.</p>
<p>What&#8217;s more it&#8217;s all open-source and provides <a href="https://realm.io/pricing/" target="_blank" rel="noopener noreferrer">really nice free plans</a>.</p>
<p>Realm.io looks very promising. I&#8217;m just a bit worried it&#8217;s almost never recommended on the web &#8211; is there something wrong with it? Maybe it&#8217;s a new stuff? Where&#8217;s a catch? Let me know if you&#8217;ve had any experience with it.</p>
<h4>SQLite-sync.com</h4>
<p>Last but maybe not least, I found <a href="http://sqlite-sync.com/" target="_blank" rel="noopener noreferrer">SQLite-sync.com</a>. The idea seems to be similar to Realm.io, however this product looks less mature. Not even 100 commits <a href="https://github.com/sqlite-sync/SQLite-sync.com/commits/master" target="_blank" rel="noopener noreferrer">on their GitHub</a> with just few contributors. Looking poor compared to <a href="https://github.com/realm/realm-dotnet" target="_blank" rel="noopener noreferrer">Realm.io&#8217;s GitHub</a> with more than 2.5k commits only for its .NET component.</p>
<p>The main (and the only?) benefit of using it would be the possibility to keep SQLite database in Xamarin.Android app. Apart from that, I don&#8217;t see any dominance over Realm.io.</p>
<h2>Summary</h2>
<p>As my research shows there are a lot of existing frameworks that help keeping data synchronized between mobile app and a remote back-end, allowing Xamarin app to work in offline-first approach. Microsoft offers great stuff in Azure, but in my opinion it&#8217;s not worth investing money for small <em>playground</em> apps.</p>
<p>For the moment I&#8217;m for Realm.io. It seems to provide very extended free plan, there&#8217;s a lot of resources on the web, folks talk about it on SO&#8230;</p>
<p>So now I&#8217;m asking you &#8211; <span style="text-decoration: underline;"><strong>do you have any experience with data sync in Xamarin apps? If yes, please share your insights and help me to choose the best approach <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>I&#8217;d be grateful for any suggestions!</p>
<p>After the framework is chosen, I will try to design the whole synchronization system and share it with you here.</p></p>
<p>The post <a href="https://www.codejourney.net/xamarin-android-asp-net-web-api-synchronization-research/">Xamarin.Android &#8211; ASP.NET web api synchronization &#8211; research</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/xamarin-android-asp-net-web-api-synchronization-research/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2345</post-id>	</item>
		<item>
		<title>Entity Framework Core &#8211; database initialization with Unit Test</title>
		<link>https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/</link>
					<comments>https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 27 Jul 2017 19:15:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[asp-net-core]]></category>
		<category><![CDATA[entity framework]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2331</guid>

					<description><![CDATA[<p>I&#8217;ve recently been presented a concept of initializing the database (creating or re-creating it) with Unit Test method. Initially I thought it&#8217;s a non-sense, but after a while of taking a deeper look&#8230; Code First approach The method of initializing the database I mentioned was used with Entity Framework Core in ASP.NET Core project, where&#8230;</p>
<p>The post <a href="https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/">Entity Framework Core &#8211; database initialization with Unit Test</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve recently been presented a concept of initializing the database (creating or re-creating it) with Unit Test method. Initially I thought it&#8217;s a non-sense, but after a while of taking a deeper look&#8230;<br />
<span id="more-2331"></span></p>
<h1>Code First approach</h1>
<p>The method of initializing the database I mentioned was used with Entity Framework Core in ASP.NET Core project, where Code First database creation approach was used. As you know, this approach implies that we create models (classes) representing our database entities in the code first and then, using an ORM system (such as EF), database structures are created.</p>
<p>&nbsp;</p>
<p>This is very convenient, especially in prototyping. I&#8217;ve developed few small or average-size ASP.NET apps and I always used Code First. However, I cannot say how it works on production as these apps were university or pet projects which I&#8217;ve never deployed on real customer&#8217;s environment. What I noticed is that creating entities using this approach is fast and quite easy.</p>
<h1>Database initialization in development phase</h1>
<p>As long as your project is in development phase, different developers are working on it and there is some database behind, but the data itself is not very important (you only need the database structure &#8211; there&#8217;s no production data in it yet), programmers often need to have the database (re)created. To make this process quick and easy, instead of using <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations" target="_blank" rel="noopener">Migrations</a> straightaway, you can define your models, <span style="color: #ff9900;">DbContext</span> and write a Unit Test method which initializes the database. Then, each developer working on the project only needs to re-run this Unit Test to have the database created.</p>
<p>What&#8217;s more, as soon as another programmer makes any change in any of the models, the others just need to re-run the Unit Test which re-creates the database and potentially fills it with sample data. There&#8217;s no need to keep any migration files/scripts in the development phase.</p>
<p>The following subsections present how to do that.</p>
<p>Examples are based on a simple ASP.NET Core MVC application called <em>CarServiceMvc</em>. I&#8217;ve used .NET Core 2.0 Preview 2 and Visual Studio 2017 15.3.0 Preview 3.0.</p>
<p>The whole source code <a href="https://github.com/dsibinski/DotNetCoreFun/tree/master/CarServiceMvc" target="_blank" rel="noopener">is available on GitHub</a>.</p>
<h3>Models</h3>
<p>First, let&#8217;s create a simple model in our application. The following class is created in <em>Models</em> folder:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist72554742" 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-car-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="Car.cs content, created by dsibinski on 06:01PM on July 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="Car.cs">
<tr>
<td id="file-car-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-car-cs-LC1" class="blob-code blob-code-inner js-file-line">  public class Car</td>
</tr>
<tr>
<td id="file-car-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-car-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-car-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-car-cs-LC3" class="blob-code blob-code-inner js-file-line">      public int Id { get; set; }</td>
</tr>
<tr>
<td id="file-car-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-car-cs-LC4" class="blob-code blob-code-inner js-file-line">      public string Producer { get; set; }</td>
</tr>
<tr>
<td id="file-car-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-car-cs-LC5" class="blob-code blob-code-inner js-file-line">      public string Model { get; set; }</td>
</tr>
<tr>
<td id="file-car-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-car-cs-LC6" class="blob-code blob-code-inner js-file-line">      public DateTime ProductionDate { get; set; }</td>
</tr>
<tr>
<td id="file-car-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-car-cs-LC7" class="blob-code blob-code-inner js-file-line">      public bool IsOnWarranty { get; set; }</td>
</tr>
<tr>
<td id="file-car-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-car-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-car-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-car-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/42de3e4c8ea259bb504939c8a3d24fea/raw/4a46ae9d2f55efd5c963d1b9bf4d5f6ecffd0ff1/Car.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/42de3e4c8ea259bb504939c8a3d24fea#file-car-cs" class="Link--inTextBlock"><br />
          Car.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<h3>DbContext</h3>
<p>Next, let&#8217;s add <span style="color: #ff9900;">CarServiceContext</span> to our application. Let&#8217;s store it in <em>ORM</em> folder.</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist72554887" 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-carservicecontext-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="CarServiceContext.cs content, created by dsibinski on 06:03PM on July 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="CarServiceContext.cs">
<tr>
<td id="file-carservicecontext-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-carservicecontext-cs-LC1" class="blob-code blob-code-inner js-file-line">  public class CarServiceContext : DbContext</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-carservicecontext-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-carservicecontext-cs-LC3" class="blob-code blob-code-inner js-file-line">      // DB connection properties injected automatically</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-carservicecontext-cs-LC4" class="blob-code blob-code-inner js-file-line">      public CarServiceContext() {}</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-carservicecontext-cs-LC5" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-carservicecontext-cs-LC6" class="blob-code blob-code-inner js-file-line">      // DB connection properties given explicitly (for Unit Tests)</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-carservicecontext-cs-LC7" class="blob-code blob-code-inner js-file-line">      public CarServiceContext(DbContextOptions options) : base(options) { }</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-carservicecontext-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-carservicecontext-cs-LC9" class="blob-code blob-code-inner js-file-line">      public DbSet&lt;Car&gt; Cars { get; set; }</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-carservicecontext-cs-LC10" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-carservicecontext-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-carservicecontext-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/ae4a1fa5c1cf2797ff3f7f6e90d3ca9b/raw/440012a73ba7d2bb210e3185d86dadec207db570/CarServiceContext.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/ae4a1fa5c1cf2797ff3f7f6e90d3ca9b#file-carservicecontext-cs" class="Link--inTextBlock"><br />
          CarServiceContext.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Constructor taking <span style="color: #ff9900;">DbContextOptions</span> has been created for Unit Tests purpose.</p>
<p>We also have a <span style="color: #ff9900;">DbSet</span> of <span style="color: #ff9900;">Cars</span>.</p>
<p>We also need to add a connection string to <em>appsettings.json</em>. For the development phase we can use <em>mssqllocaldb </em>included within Visual Studio:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist72555034" 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-appsettings-json" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-json  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="appsettings.json content, created by dsibinski on 06:05PM on July 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="appsettings.json">
<tr>
<td id="file-appsettings-json-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-appsettings-json-LC1" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-appsettings-json-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-appsettings-json-LC2" class="blob-code blob-code-inner js-file-line">    &quot;Logging&quot;: {</td>
</tr>
<tr>
<td id="file-appsettings-json-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-appsettings-json-LC3" class="blob-code blob-code-inner js-file-line">      &quot;IncludeScopes&quot;: false,</td>
</tr>
<tr>
<td id="file-appsettings-json-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-appsettings-json-LC4" class="blob-code blob-code-inner js-file-line">      &quot;Debug&quot;: {</td>
</tr>
<tr>
<td id="file-appsettings-json-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-appsettings-json-LC5" class="blob-code blob-code-inner js-file-line">        &quot;LogLevel&quot;: {</td>
</tr>
<tr>
<td id="file-appsettings-json-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-appsettings-json-LC6" class="blob-code blob-code-inner js-file-line">          &quot;Default&quot;: &quot;Warning&quot;</td>
</tr>
<tr>
<td id="file-appsettings-json-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-appsettings-json-LC7" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-appsettings-json-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-appsettings-json-LC8" class="blob-code blob-code-inner js-file-line">      },</td>
</tr>
<tr>
<td id="file-appsettings-json-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-appsettings-json-LC9" class="blob-code blob-code-inner js-file-line">      &quot;Console&quot;: {</td>
</tr>
<tr>
<td id="file-appsettings-json-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-appsettings-json-LC10" class="blob-code blob-code-inner js-file-line">        &quot;LogLevel&quot;: {</td>
</tr>
<tr>
<td id="file-appsettings-json-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-appsettings-json-LC11" class="blob-code blob-code-inner js-file-line">          &quot;Default&quot;: &quot;Warning&quot;</td>
</tr>
<tr>
<td id="file-appsettings-json-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-appsettings-json-LC12" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-appsettings-json-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-appsettings-json-LC13" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-appsettings-json-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-appsettings-json-LC14" class="blob-code blob-code-inner js-file-line">    },</td>
</tr>
<tr>
<td id="file-appsettings-json-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-appsettings-json-LC15" class="blob-code blob-code-inner js-file-line">    &quot;ConnectionStrings&quot;: {</td>
</tr>
<tr>
<td id="file-appsettings-json-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-appsettings-json-LC16" class="blob-code blob-code-inner js-file-line">      &quot;DefaultConnection&quot;: &quot;Server=(localdb)\\mssqllocaldb;Database=aspnet-Demo;Trusted_Connection=True;MultipleActiveResultSets=true&quot;</td>
</tr>
<tr>
<td id="file-appsettings-json-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-appsettings-json-LC17" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-appsettings-json-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-appsettings-json-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/cd5658a4b56bc1d3f846ed557fc3ffb6/raw/15151d4f67592c904da85c66fdebbf07747d7e64/appsettings.json" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/cd5658a4b56bc1d3f846ed557fc3ffb6#file-appsettings-json" class="Link--inTextBlock"><br />
          appsettings.json<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In the end, <em>Startup.cs</em> should be modified to have our <span style="color: #ff9900;">DbContext <span style="color: #000000;">registered:</span></span></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist72555195" 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-startup_dbcontext-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="Startup_dbContext.cs content, created by dsibinski on 06:07PM on July 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="Startup_dbContext.cs">
<tr>
<td id="file-startup_dbcontext-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-startup_dbcontext-cs-LC1" class="blob-code blob-code-inner js-file-line">  public void ConfigureServices(IServiceCollection services)</td>
</tr>
<tr>
<td id="file-startup_dbcontext-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-startup_dbcontext-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-startup_dbcontext-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-startup_dbcontext-cs-LC3" class="blob-code blob-code-inner js-file-line">      services.AddDbContext&lt;CarServiceContext&gt;(o =&gt;</td>
</tr>
<tr>
<td id="file-startup_dbcontext-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-startup_dbcontext-cs-LC4" class="blob-code blob-code-inner js-file-line">          o.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</td>
</tr>
<tr>
<td id="file-startup_dbcontext-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-startup_dbcontext-cs-LC5" class="blob-code blob-code-inner js-file-line">      services.AddMvc();</td>
</tr>
<tr>
<td id="file-startup_dbcontext-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-startup_dbcontext-cs-LC6" 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/b30022b5644925bf8423e2026ad86bb2/raw/6c23b8f62800f9e0fd76aabeb04b7d116a7f2a59/Startup_dbContext.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/b30022b5644925bf8423e2026ad86bb2#file-startup_dbcontext-cs" class="Link--inTextBlock"><br />
          Startup_dbContext.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Now we can add a new controller for the <span style="color: #ff9900;">Car</span> model we created, so Visual Studio scaffolds all basic views. However, if we try to launch the application calling one of <span style="color: #ff9900;">CarsController</span>&#8216;s methods, we get the following exception:</p>
<p><figure id="attachment_2334" aria-describedby="caption-attachment-2334" style="width: 461px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2334" data-permalink="https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/carnotfound/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?fit=1065%2C452&amp;ssl=1" data-orig-size="1065,452" 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="CarNotFound" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?fit=300%2C127&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?fit=1024%2C435&amp;ssl=1" class="wp-image-2334" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?resize=461%2C195&#038;ssl=1" alt="" width="461" height="195" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?resize=300%2C127&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?resize=768%2C326&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?resize=1024%2C435&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?resize=720%2C306&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarNotFound.png?w=1065&amp;ssl=1 1065w" sizes="auto, (max-width: 461px) 100vw, 461px" /></a><figcaption id="caption-attachment-2334" class="wp-caption-text">Car not found</figcaption></figure></p>
<p>So, let&#8217;s see how we can initialize our database with Unit Test.</p>
<h3>Database initialization Unit Test</h3>
<p>Firstly, new project should be added to our solution. Let&#8217;s add a new one of type Unit Test Project (.NET Core) and call it <em>CarsServiceMvc.Tests</em>.</p>
<p>We would like to use <span style="color: #ff9900;">DefaultConnection</span> connection string defined in the main project. For that purpose, we right click on the <em>Tests</em> project, select <em>Add -&gt; Existing item &#8230;,</em> go back to the main project&#8217;s folder and select <em>appsettings.json</em> file, adding it as a link:</p>
<p><figure id="attachment_2335" aria-describedby="caption-attachment-2335" style="width: 349px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2335" data-permalink="https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/addfileaslink/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?fit=699%2C471&amp;ssl=1" data-orig-size="699,471" 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="AddFileAsLink" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?fit=300%2C202&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?fit=699%2C471&amp;ssl=1" class="wp-image-2335 " src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?resize=349%2C235&#038;ssl=1" alt="" width="349" height="235" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?resize=300%2C202&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/AddFileAsLink.png?w=699&amp;ssl=1 699w" sizes="auto, (max-width: 349px) 100vw, 349px" /></a><figcaption id="caption-attachment-2335" class="wp-caption-text">Adding config file as a link</figcaption></figure></p>
<p>This file should also be copied to the output directory of <em>Tests</em> project (it can be set in the Properties of the linked file).</p>
<p>Now we can add a new <em>TestClass</em> called <span style="color: #ff9900;">CarServiceContextInitTests</span> which will contain our db initialization Unit Test. In order to be able to access the same database as in the main project, we need to create few properties and configure necessary settings in the constructor of the test class:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist72556847" 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-carservicecontextinittests_ctor-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="CarServiceContextInitTests_ctor.cs content, created by dsibinski on 06:28PM on July 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="CarServiceContextInitTests_ctor.cs">
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC1" class="blob-code blob-code-inner js-file-line">  [TestClass]</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC2" class="blob-code blob-code-inner js-file-line">  public class CarServiceContextInitTests</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC3" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC4" class="blob-code blob-code-inner js-file-line">      // to have the same Configuration object as in Startup</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC5" class="blob-code blob-code-inner js-file-line">      private IConfigurationRoot _configuration;</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC6" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC7" class="blob-code blob-code-inner js-file-line">      // represents database&#39;s configuration</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC8" class="blob-code blob-code-inner js-file-line">      private DbContextOptions&lt;CarServiceContext&gt; _options;</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC10" class="blob-code blob-code-inner js-file-line">      public CarServiceContextInitTests()</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC11" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC12" class="blob-code blob-code-inner js-file-line">          var builder = new ConfigurationBuilder()</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC13" class="blob-code blob-code-inner js-file-line">              .SetBasePath(Directory.GetCurrentDirectory())</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC14" class="blob-code blob-code-inner js-file-line">              .AddJsonFile(&quot;appsettings.json&quot;);</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC16" class="blob-code blob-code-inner js-file-line">          _configuration = builder.Build();</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC17" class="blob-code blob-code-inner js-file-line">          _options = new DbContextOptionsBuilder&lt;CarServiceContext&gt;()</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC18" class="blob-code blob-code-inner js-file-line">              .UseSqlServer(_configuration.GetConnectionString(&quot;DefaultConnection&quot;))</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC19" class="blob-code blob-code-inner js-file-line">              .Options;</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC20" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-carservicecontextinittests_ctor-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-carservicecontextinittests_ctor-cs-LC21" 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/f8cbd51dbfb33ef360e16d1d56e164e1/raw/cda90ac2bbb252cb4650f89790472a56f171ee9c/CarServiceContextInitTests_ctor.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/f8cbd51dbfb33ef360e16d1d56e164e1#file-carservicecontextinittests_ctor-cs" class="Link--inTextBlock"><br />
          CarServiceContextInitTests_ctor.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>As the <em>appsettings.json</em> file is copied to the <em>Tests</em> project&#8217;s output directory, we can read its contents with <span style="color: #ff9900;">ConfigurationBuilder</span> class. After, we just initialize <span style="color: #ff9900;">_options</span> property with the db connection settings.</p>
<p>Finally we can add the desired Unit Test method:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist72557144" 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-initializedatabasewithdatatest_method-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="InitializeDatabaseWithDataTest_method.cs content, created by dsibinski on 06:32PM on July 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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="InitializeDatabaseWithDataTest_method.cs">
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC1" class="blob-code blob-code-inner js-file-line">  [TestMethod]</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC2" class="blob-code blob-code-inner js-file-line">        public void InitializeDatabaseWithDataTest()</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC3" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC4" class="blob-code blob-code-inner js-file-line">            using (var context = new CarServiceContext(_options))</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC5" class="blob-code blob-code-inner js-file-line">            {</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC6" class="blob-code blob-code-inner js-file-line">                context.Database.EnsureDeleted();</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC7" class="blob-code blob-code-inner js-file-line">                context.Database.EnsureCreated();</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC9" class="blob-code blob-code-inner js-file-line">                var car1 = new Car()</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC10" class="blob-code blob-code-inner js-file-line">                {</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC11" class="blob-code blob-code-inner js-file-line">                    Producer = &quot;Volkswagen&quot;,</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC12" class="blob-code blob-code-inner js-file-line">                    Model = &quot;Golf IV&quot;,</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC13" class="blob-code blob-code-inner js-file-line">                    ProductionDate = new DateTime(2009, 01, 01),</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC14" class="blob-code blob-code-inner js-file-line">                    IsOnWarranty = false</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC15" class="blob-code blob-code-inner js-file-line">                };</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC17" class="blob-code blob-code-inner js-file-line">                var car2 = new Car()</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC18" class="blob-code blob-code-inner js-file-line">                {</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC19" class="blob-code blob-code-inner js-file-line">                    Producer = &quot;Peugeot&quot;,</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC20" class="blob-code blob-code-inner js-file-line">                    Model = &quot;206&quot;,</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC21" class="blob-code blob-code-inner js-file-line">                    ProductionDate = new DateTime(2000, 01, 01),</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC22" class="blob-code blob-code-inner js-file-line">                    IsOnWarranty = false</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC23" class="blob-code blob-code-inner js-file-line">                };</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC24" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC25" class="blob-code blob-code-inner js-file-line">                context.Cars.AddRange(car1, car2);</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC26" class="blob-code blob-code-inner js-file-line">                context.SaveChanges();</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC27" class="blob-code blob-code-inner js-file-line">            }</td>
</tr>
<tr>
<td id="file-initializedatabasewithdatatest_method-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-initializedatabasewithdatatest_method-cs-LC28" 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/933f0a51f858026ce1643686e44996d5/raw/fde019a96e43fedb4e39344424376fc023088984/InitializeDatabaseWithDataTest_method.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/933f0a51f858026ce1643686e44996d5#file-initializedatabasewithdatatest_method-cs" class="Link--inTextBlock"><br />
          InitializeDatabaseWithDataTest_method.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 important parts of this code:</p>
<p>Line 4: we used <span style="color: #ff9900;">_options</span> property to configure the <span style="color: #ff9900;">CarServiceContext <span style="color: #000000;">thanks to its second constructor<br />
</span></span></p>
<p>Lines 6 and 7: <span style="color: #ff9900;">EnsureDeleted()</span> method is called before <span style="color: #ff9900;">EnsureCreated()</span>, which makes the db being re-created every time Unit Test is run.</p>
<p>After, there&#8217;s just creation of two <span style="color: #ff9900;">Car</span> objects and inserting these into the database.</p>
<p>After this Unit Test is run, <em>Cars</em> table is created in the local database with two sample rows. When we launch the application there&#8217;s no more error:</p>
<p><figure id="attachment_2337" aria-describedby="caption-attachment-2337" style="width: 574px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2337" data-permalink="https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/carslistmvc/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?fit=1000%2C535&amp;ssl=1" data-orig-size="1000,535" 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="CarsListMvc" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?fit=300%2C161&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?fit=1000%2C535&amp;ssl=1" class="wp-image-2337" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?resize=574%2C308&#038;ssl=1" alt="" width="574" height="308" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?resize=300%2C161&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?resize=768%2C411&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?resize=720%2C385&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/07/CarsListMvc.png?w=1000&amp;ssl=1 1000w" sizes="auto, (max-width: 574px) 100vw, 574px" /></a><figcaption id="caption-attachment-2337" class="wp-caption-text">Cars list</figcaption></figure></p>
<p>From now on, every developer who starts working on the project only executes our unit test and his/her local database is created and filled with sample data.</p>
<p>Moreover, when there&#8217;s any change in the model class, there&#8217;s just one Unit Test to modify (e.g. if <strong>Required</strong> column is added to the model) and the other programmers just re-execute the Unit Test and database is up-to-date and ready to work with.</p>
<h1>Database initialization on production</h1>
<p>The Unit Test approach of database initialization could also be used on production environment, for instance when the application is to be installed for the first time on customer&#8217;s environment. We can create another Unit Test which creates the database structures, but doesn&#8217;t fill it with any data in a separate project. Then such Unit Tests project can be compiled to an executable and launched on production environment.</p>
<p>I know people who used it on production, but I don&#8217;t think I&#8217; be brave enough to go that far <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>The database initialization with Unit Test is kind of a new approach I&#8217;ve never been thinking about. In my opinion it could be used with success during development phase, when the data in the database is not a production one. As soon as customer starts creating some business data in the application, it would probably make less sense to drop and create brand new database each time a developer starts working on the project (most of the bugs/issues we solve on production are dependent from the business data in the application).</p>
<p><span style="text-decoration: underline;"><strong>Did you know this approach of creating the database with Unit Test? What are the techniques you use to initialize the database when working with other developers? Let me know, I&#8217;m deeply interested how it looks on your daily basis <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/entity-framework-core-database-initialization-with-unit-test/">Entity Framework Core &#8211; database initialization with Unit Test</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/entity-framework-core-database-initialization-with-unit-test/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2331</post-id>	</item>
		<item>
		<title>Xamarin.Android &#8211; debugging via WiFi</title>
		<link>https://www.codejourney.net/xamarin-android-debugging-via-wifi/</link>
					<comments>https://www.codejourney.net/xamarin-android-debugging-via-wifi/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Tue, 30 May 2017 21:08:38 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2296</guid>

					<description><![CDATA[<p>In this short post, I&#8217;m going to show you a very handy feature of Android Debug Bridge (adb) &#8211; possibility to debug Xamarin.Android apps in Visual Studio via WiFi connection. Using ADB to debug Android apps By default, adb is configured to &#8220;map&#8221; Android devices connected via USB ports to the computer as debug devices, which are then&#8230;</p>
<p>The post <a href="https://www.codejourney.net/xamarin-android-debugging-via-wifi/">Xamarin.Android &#8211; debugging via WiFi</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this short post, I&#8217;m going to show you a very handy feature of <a href="https://developer.android.com/studio/command-line/adb.html" target="_blank" rel="noopener noreferrer">Android Debug Bridge</a> (<em>adb</em>) &#8211; possibility to debug Xamarin.Android apps in Visual Studio via WiFi connection.<br />
<span id="more-2296"></span></p>
<h2>Using ADB to debug Android apps</h2>
<p>By default, <em>adb</em> is configured to &#8220;map&#8221; Android devices connected via USB ports to the computer as <em>debug devices</em>, which are then available e.g. in Visual Studio as the device on which our app can be deployed and debugged. In may cases we debug apps on Android emulators, which is frequently fair enough, but at some point we need to make our tests on a physical device.</p>
<p>It may not be very comfortable to have the phone connected using USB cable all the time, especially when testing some physical sensors like accelerometer or gyroscope. For such purposes, ADB gives us the possibility to connect Android devices via WiFi instead of USB. Let&#8217;s see how to configure it.</p>
<h2>Configure ADB to work on WiFi</h2>
<p>The first requirement is &#8211; obviously &#8211; that both our development PC and Android device must be connected to the same WiFi network. Then we need to find out what is the IP address of our Android device &#8211; it can be checked by going to <strong>Settings -&gt; WiFi -&gt; Menu &#8211; Advanced settings </strong>(Android 6.0):</p>
<p><figure id="attachment_2297" aria-describedby="caption-attachment-2297" style="width: 222px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2297" data-permalink="https://www.codejourney.net/xamarin-android-debugging-via-wifi/huaweip8_ip/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.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="HuaweiP8_IP" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?fit=169%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?fit=576%2C1024&amp;ssl=1" class="wp-image-2297" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?resize=222%2C394&#038;ssl=1" alt="" width="222" height="394" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?resize=169%2C300&amp;ssl=1 169w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?resize=768%2C1365&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?resize=576%2C1024&amp;ssl=1 576w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?resize=720%2C1280&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/HuaweiP8_IP.png?w=1080&amp;ssl=1 1080w" sizes="auto, (max-width: 222px) 100vw, 222px" /></a><figcaption id="caption-attachment-2297" class="wp-caption-text">Android 6.0 &#8211; IP address</figcaption></figure></p>
<p>As soon as you have IP address of the device noted, <strong>connect it to the computer via USB port</strong>.</p>
<p>Now we need to use <em>adb.exe</em> to configure it for connecting with the device via WiFi. You can either add system environmental variable pointing to where the <em>adb.exe</em> is stored or just open <em>cmd</em>, go to the catalogue where it&#8217;s located (<em>Android\platform-tools\</em>) and execute the following commands:</p>
<ol>
<li>Change ADB to listen on TCP port:</li>
</ol>
<pre><pre class="brush: bash; title: ; notranslate">adb tcpip 5555</pre>
<p>This will make ADB listening on TCP port 5555 instead of USB ports (<strong>NOTE</strong>: since now the computer won&#8217;t listen to any devices connected by USB ports):</p>
<p><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2307" data-permalink="https://www.codejourney.net/xamarin-android-debugging-via-wifi/cmd_1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?fit=553%2C58&amp;ssl=1" data-orig-size="553,58" 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="cmd_1" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?fit=300%2C31&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?fit=553%2C58&amp;ssl=1" class="aligncenter wp-image-2307" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?resize=319%2C33&#038;ssl=1" alt="" width="319" height="33" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?resize=300%2C31&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_1.png?w=553&amp;ssl=1 553w" sizes="auto, (max-width: 319px) 100vw, 319px" /></a></p>
<p>Now,<strong> disconnect the Android device from USB port</strong>.</p>
<p>2. Make ADB connect to your Android device:</p>
<pre><pre class="brush: bash; title: ; notranslate">adb connect 192.168.0.101:5555</pre>
<p>This command is used to connect to Android device (of course IP address must be changed with your device&#8217;s one) on port 5555 using WiFi:</p>
<p><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2308" data-permalink="https://www.codejourney.net/xamarin-android-debugging-via-wifi/cmd_2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?fit=723%2C55&amp;ssl=1" data-orig-size="723,55" 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="cmd_2" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?fit=300%2C23&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?fit=723%2C55&amp;ssl=1" class="aligncenter wp-image-2308" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?resize=430%2C33&#038;ssl=1" alt="" width="430" height="33" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?resize=300%2C23&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?resize=720%2C55&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/cmd_2.png?w=723&amp;ssl=1 723w" sizes="auto, (max-width: 430px) 100vw, 430px" /></a></p>
<p>
3. Since now you should see the device in Visual Studio connected using WiFi connection:</p>
<p><figure id="attachment_2309" aria-describedby="caption-attachment-2309" style="width: 671px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2309" data-permalink="https://www.codejourney.net/xamarin-android-debugging-via-wifi/huawei_connectedwifi/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?fit=1150%2C65&amp;ssl=1" data-orig-size="1150,65" 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="Huawei_connectedWifi" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?fit=300%2C17&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?fit=1024%2C58&amp;ssl=1" class="wp-image-2309" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?resize=671%2C38&#038;ssl=1" alt="" width="671" height="38" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?resize=300%2C17&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?resize=768%2C43&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?resize=1024%2C58&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?resize=720%2C41&amp;ssl=1 720w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Huawei_connectedWifi.png?w=1150&amp;ssl=1 1150w" sizes="auto, (max-width: 671px) 100vw, 671px" /></a><figcaption id="caption-attachment-2309" class="wp-caption-text">WiFi Android device visible in Visual Studio</figcaption></figure></p>
<p>and you can of course deploy the app remotely on the device and debug 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>4. As soon as you&#8217;re done with WiFi debugging, run the following command:</p>
<pre><pre class="brush: bash; title: ; notranslate">adb usb</pre>
<p>It will make ADB listening for USB devices again:</p>
<p><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2310" data-permalink="https://www.codejourney.net/xamarin-android-debugging-via-wifi/commands_usbrestored/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?fit=479%2C55&amp;ssl=1" data-orig-size="479,55" 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;1496180723&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;1&quot;}" data-image-title="Commands_UsbRestored" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?fit=300%2C34&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?fit=479%2C55&amp;ssl=1" class="aligncenter wp-image-2310" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?resize=353%2C40&#038;ssl=1" alt="" width="353" height="40" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?resize=300%2C34&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Commands_UsbRestored.jpg?w=479&amp;ssl=1 479w" sizes="auto, (max-width: 353px) 100vw, 353px" /></a></p>
<p><strong>TIP</strong>: if during performing any <em>cmd</em> commands <em>adb.exe </em>is stuck or not reacting, try plugging out and re-plugging in your Android device to USB port.</p>
<h2>Summary</h2>
<p>This post described how to use remote debugging on Android devices using WiFi connection.</p>
<p>I hope you&#8217;ll find it useful <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/xamarin-android-debugging-via-wifi/">Xamarin.Android &#8211; debugging via WiFi</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/xamarin-android-debugging-via-wifi/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2296</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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_SecondTab.png?fit=169%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_AfterRotateFirstTab.png?fit=300%2C169&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_rotate2-1.png?fit=300%2C146&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DatePicker.png?fit=169%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/Event_DateSelection.png?fit=169%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_noInv_UML.jpg?fit=300%2C57&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_noInv_debug-1.png?fit=300%2C107&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tm_withInv_UML.jpg?fit=300%2C59&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1tM_withInv_debug.png?fit=300%2C101&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRec.jpg?fit=300%2C74&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_noRev_debug.png?fit=300%2C124&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRec.jpg?fit=300%2C74&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/1t1_withRev_debug.png?fit=300%2C116&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/erd-many-to-many-1.jpg?fit=300%2C235&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/personContainsEvents-1.png?fit=300%2C118&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/eventContainsParticipants-1.png?fit=300%2C126&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_MainWithTabs.png?fit=169%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_PersonAdding.png?fit=169%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/05/MoneyBack_List.png?fit=169%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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;<span class="pl-ent">LinearLayout</span> <span class="pl-e">xmlns</span><span class="pl-e">:</span><span class="pl-e">android</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>http://schemas.android.com/apk/res/android<span class="pl-pds">&quot;</span></span></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">    <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">orientation</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>vertical<span class="pl-pds">&quot;</span></span></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">    <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_width</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>match_parent<span class="pl-pds">&quot;</span></span></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">    <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_height</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>match_parent<span class="pl-pds">&quot;</span></span></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">    <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">minWidth</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>25px<span class="pl-pds">&quot;</span></span></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">    <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">minHeight</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>25px<span class="pl-pds">&quot;</span></span>&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;<span class="pl-ent">FrameLayout</span></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">        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">minWidth</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>25px<span class="pl-pds">&quot;</span></span></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">        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">minHeight</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>25px<span class="pl-pds">&quot;</span></span></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">        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_width</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>match_parent<span class="pl-pds">&quot;</span></span></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">        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">layout_height</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>match_parent<span class="pl-pds">&quot;</span></span></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">        <span class="pl-e">android</span><span class="pl-e">:</span><span class="pl-e">id</span>=<span class="pl-s"><span class="pl-pds">&quot;</span>@+id/tabFragmentsContainer<span class="pl-pds">&quot;</span></span> /&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;/<span class="pl-ent">LinearLayout</span>&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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PL.png?fit=169%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_EN.png?fit=169%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound.jpg?fit=300%2C51&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ResourceNotFound_Test_Reference.jpg?fit=270%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Resources_Strings_Copied.jpg?fit=300%2C85&amp;ssl=1" 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>Android Layout Types</title>
		<link>https://www.codejourney.net/android-layout-types/</link>
					<comments>https://www.codejourney.net/android-layout-types/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 02 Apr 2017 06:55:49 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[dajsiepoznac2017]]></category>
		<category><![CDATA[xamarin]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=1695</guid>

					<description><![CDATA[<p>If you&#8217;re just an Android user, you may not even know that each screen in your application has controls composed within different Layouts. Let&#8217;s see what are the main Layout Types in designing Android app. What is a Layout ? Layout defines a visual structure of an Activity (or app widget). It may be considered as&#8230;</p>
<p>The post <a href="https://www.codejourney.net/android-layout-types/">Android Layout Types</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>If you&#8217;re just an Android user, you may not even know that each screen in your application has controls composed within different <em>Layouts</em>. Let&#8217;s see what are the main Layout Types in designing Android app.<br />
<span id="more-1695"></span></p>
<h2>What is a Layout ?</h2>
<p><strong>Layout defines a visual structure</strong> of an Activity (or <a href="https://developer.android.com/guide/topics/appwidgets/index.html" target="_blank" rel="noopener">app widget</a>). It may be considered as a set of rules according to which controls (buttons, text fields, input fields etc.) are placed on the <em>View</em>.</p>
<h2>Layouts structure</h2>
<p>Basically, user interface in Android apps is built using <em>Layouts</em>. Each <em>Layout</em> is a subclass of <span style="color: #ff9900;">ViewGroup</span> class, which derives from <span style="color: #ff9900;">View</span> class, which is the basic UI building block. <span style="color: #ff9900;">View</span> is the base class for buttons, text fields etc., more precisely: for <a href="https://developer.xamarin.com/api/namespace/Android.Widget/" target="_blank" rel="noopener">widgets</a> (don&#8217;t confuse it with app widgets you place on your Android screen <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 following diagram presents this hierarchy based on <em><span style="color: #ff9900;">RelativeLayout</span></em>:</p>
<p><figure id="attachment_1717" aria-describedby="caption-attachment-1717" style="width: 615px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1717" data-permalink="https://www.codejourney.net/android-layout-types/android_view_hierarchy_diagram/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Android_view_hierarchy_diagram.png?fit=615%2C272&amp;ssl=1" data-orig-size="615,272" 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_view_hierarchy_diagram" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Android_view_hierarchy_diagram.png?fit=300%2C133&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Android_view_hierarchy_diagram.png?fit=615%2C272&amp;ssl=1" class="aligncenter size-full wp-image-1717" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Android_view_hierarchy_diagram.png?resize=615%2C272&#038;ssl=1" alt="Android_view_hierarchy_diagram.png" width="615" height="272" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Android_view_hierarchy_diagram.png?w=615&amp;ssl=1 615w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Android_view_hierarchy_diagram.png?resize=300%2C133&amp;ssl=1 300w" sizes="auto, (max-width: 615px) 100vw, 615px" /><figcaption id="caption-attachment-1717" class="wp-caption-text">RelativeLayout hierarchy, source: <a href="http://www.techotopia.com/index.php/Understanding_Android_Views,_View_Groups_and_Layouts" target="_blank" rel="noopener">techotopia.com</a></figcaption></figure></p>
<p>Let&#8217;s now see what are the most important Layout Types. Below each screenshot used to present a particular Layout Type you can find its <span style="text-decoration: underline;">source</span>, which leads to a tutorial or more detailed explanation on how to work with it.</p>
<h2>Linear Layout</h2>
<p><em>LinearLayout</em> is the most basic type of <em>Layout</em>. When Android app is created in Visual Studio 2017, its <span style="color: #ff9900;">MainActivity</span> has by default <em>LinearLayout</em> set:</p>
<p><figure id="attachment_1725" aria-describedby="caption-attachment-1725" style="width: 569px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1725" data-permalink="https://www.codejourney.net/android-layout-types/linear_moneyback/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?fit=847%2C327&amp;ssl=1" data-orig-size="847,327" 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;1491120503&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;1&quot;}" data-image-title="Linear_MoneyBack" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?fit=300%2C116&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?fit=847%2C327&amp;ssl=1" class="wp-image-1725" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?resize=569%2C220&#038;ssl=1" alt="Linear_MoneyBack" width="569" height="220" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?w=847&amp;ssl=1 847w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?resize=300%2C116&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?resize=768%2C297&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Linear_MoneyBack.jpg?resize=720%2C278&amp;ssl=1 720w" sizes="auto, (max-width: 569px) 100vw, 569px" /><figcaption id="caption-attachment-1725" class="wp-caption-text">LinearLayout set on MoneyBack&#8217;s MainActivity</figcaption></figure></p>
<p>This type of <em>Layout</em> enforces you to put your controls in a linear direction, either horizontally or vertically:</p>
<p><figure id="attachment_1730" aria-describedby="caption-attachment-1730" style="width: 351px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1730" data-permalink="https://www.codejourney.net/android-layout-types/linearlayout/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?fit=788%2C517&amp;ssl=1" data-orig-size="788,517" 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="LinearLayout" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?fit=300%2C197&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?fit=788%2C517&amp;ssl=1" class=" size-full wp-image-1730 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?resize=351%2C230&#038;ssl=1" alt="LinearLayout.png" width="351" height="230" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?w=788&amp;ssl=1 788w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?resize=300%2C197&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?resize=768%2C504&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/LinearLayout.png?resize=720%2C472&amp;ssl=1 720w" sizes="auto, (max-width: 351px) 100vw, 351px" /><figcaption id="caption-attachment-1730" class="wp-caption-text">LinearLayout, <a href="http://android4beginners.com/2013/07/lesson-2-1-how-to-build-android-app-with-simple-but-powerful-linearlayout-plus-layout-orientation-as-well-as-size-and-weight-of-elements/" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<h2>Relative Layout</h2>
<p><em>RelativeLayout</em> enforces to display elements in relations to each other. You can specify that, for instance, one UI element can be said to be placed on the left of another element, or on the bottom of another etc. Each UI element can also be positioned according to the layout&#8217;s borders (e.g. aligned to the right):</p>
<p><figure id="attachment_1739" aria-describedby="caption-attachment-1739" style="width: 521px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1739" data-permalink="https://www.codejourney.net/android-layout-types/relativelayout_android/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?fit=801%2C501&amp;ssl=1" data-orig-size="801,501" 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="RelativeLayout_Android" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?fit=300%2C188&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?fit=801%2C501&amp;ssl=1" class="aligncenter wp-image-1739" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?resize=521%2C326&#038;ssl=1" alt="RelativeLayout_Android.png" width="521" height="326" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?w=801&amp;ssl=1 801w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?resize=300%2C188&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?resize=768%2C480&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/RelativeLayout_Android.png?resize=720%2C450&amp;ssl=1 720w" sizes="auto, (max-width: 521px) 100vw, 521px" /><figcaption id="caption-attachment-1739" class="wp-caption-text">RelativeLayout, <a href="https://www.skynils.com/relative-layout-in-android/" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<p><em>RelativeLayout</em> is very powerful. Consider that for building mobile apps&#8217; interfaces these can be run on multiple devices with different screens&#8217; resolutions. <em>RelativeLayout</em> allows (if properly built, of course) to adjust your set of controls easily to almost every type of screen. It&#8217;s quite specific and I personally found it difficult to understand and use initially, but it seems to be worth it.</p>
<h2>Table Layout</h2>
<p>As its name suggests, <em>TableLayout</em> allows to group elements into rows and columns:</p>
<p><figure id="attachment_1746" aria-describedby="caption-attachment-1746" style="width: 248px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1746" data-permalink="https://www.codejourney.net/android-layout-types/tablelayout_android/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/TableLayout_Android.png?fit=287%2C400&amp;ssl=1" data-orig-size="287,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="TableLayout_Android" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/TableLayout_Android.png?fit=215%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/TableLayout_Android.png?fit=287%2C400&amp;ssl=1" class="aligncenter wp-image-1746" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/TableLayout_Android.png?resize=248%2C346&#038;ssl=1" alt="TableLayout_Android.jpg" width="248" height="346" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/TableLayout_Android.png?w=287&amp;ssl=1 287w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/TableLayout_Android.png?resize=215%2C300&amp;ssl=1 215w" sizes="auto, (max-width: 248px) 100vw, 248px" /><figcaption id="caption-attachment-1746" class="wp-caption-text">TableLayout, <a href="https://www.tutorialspoint.com/android/android_table_layout.htm" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<p>May be useful when displaying some statistics or reports.</p>
<h2>Grid View</h2>
<p><em>GridView</em> displays items in two-dimensional grid. The list can be easily scrolled. This type of <em>Layout</em> is often used on screens displaying photos or similar sets of &#8220;blocks&#8221; to click:</p>
<p><figure id="attachment_1753" aria-describedby="caption-attachment-1753" style="width: 436px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1753" data-permalink="https://www.codejourney.net/android-layout-types/gridview_android/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/GridView_Android.png?fit=580%2C491&amp;ssl=1" data-orig-size="580,491" 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="GridView_Android" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/GridView_Android.png?fit=300%2C254&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/GridView_Android.png?fit=580%2C491&amp;ssl=1" class="aligncenter wp-image-1753" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/GridView_Android.png?resize=436%2C369&#038;ssl=1" alt="GridView_Android.png" width="436" height="369" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/GridView_Android.png?w=580&amp;ssl=1 580w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/GridView_Android.png?resize=300%2C254&amp;ssl=1 300w" sizes="auto, (max-width: 436px) 100vw, 436px" /><figcaption id="caption-attachment-1753" class="wp-caption-text">GridView, <a href="http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<h2>Tab Layout</h2>
<p><a href="https://developer.xamarin.com/guides/android/user_interface/tab_layout/" target="_blank" rel="noopener">Tabbed layouts</a> allow to introduce tabs in our Android application. Then, a single Activity may contain several tabs and user can easily switch between them. On each tab you can use different type of Layout.</p>
<p>Consider that tabs design has changed between Android 2.X and 4.X:</p>
<p><figure id="attachment_1764" aria-describedby="caption-attachment-1764" style="width: 474px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1764" data-permalink="https://www.codejourney.net/android-layout-types/tabs_android/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Tabs_Android.png?fit=550%2C194&amp;ssl=1" data-orig-size="550,194" 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="Tabs_Android" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Tabs_Android.png?fit=300%2C106&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Tabs_Android.png?fit=550%2C194&amp;ssl=1" class=" wp-image-1764 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Tabs_Android.png?resize=474%2C167&#038;ssl=1" alt="Tabs_Android.png" width="474" height="167" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Tabs_Android.png?w=550&amp;ssl=1 550w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/Tabs_Android.png?resize=300%2C106&amp;ssl=1 300w" sizes="auto, (max-width: 474px) 100vw, 474px" /><figcaption id="caption-attachment-1764" class="wp-caption-text">Tabs, <a href="https://developer.xamarin.com/guides/android/user_interface/tab_layout/" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<h2>List View</h2>
<p><em>ListView</em> allows to display a list of items. It may be used in multiple places, from short lists of menu options to long list of emails or news feed. It allows to easily and quickly present a list of items:</p>
<p><figure id="attachment_1778" aria-describedby="caption-attachment-1778" style="width: 267px" class="wp-caption aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="1778" data-permalink="https://www.codejourney.net/android-layout-types/listview_android/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ListView_Android.png?fit=320%2C480&amp;ssl=1" data-orig-size="320,480" 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="ListView_Android" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ListView_Android.png?fit=200%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ListView_Android.png?fit=320%2C480&amp;ssl=1" class=" size-full wp-image-1778 aligncenter" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ListView_Android.png?resize=267%2C401&#038;ssl=1" alt="ListView_Android.png" width="267" height="401" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ListView_Android.png?w=320&amp;ssl=1 320w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/ListView_Android.png?resize=200%2C300&amp;ssl=1 200w" sizes="auto, (max-width: 267px) 100vw, 267px" /><figcaption id="caption-attachment-1778" class="wp-caption-text">ListView, <a href="http://windrealm.org/tutorials/android/android-listview.php" target="_blank" rel="noopener">source</a></figcaption></figure></p>
<p>I used it in <em>MoneyBack</em> for displaying a very simple list of people from the database. You can check how it&#8217;s done in <a href="https://gist.github.com/dsibinski/b6dcbf1dc0956b584188282c2cb832a2" target="_blank" rel="noopener">this public Gist</a> (there is even no AXML layout file for it, it&#8217;s just an Activity class).</p>
<p>However, Android and Xamarin teams recommend to use <em>RecyclerView</em> for new apps development, which is said to be more advanced and flexible version of<em> ListView</em>. I just noticed it seems to be a bit more complex to set up. You can check more details <a href="https://developer.xamarin.com/guides/android/user_interface/recyclerview/" target="_blank" rel="noopener">here.</a></p>
<h2>Summary</h2>
<p>We&#8217;ve explored some basic Layout Types that can be used for grouping UI elements in Android application. Remember that all types of layouts we&#8217;ve gone through may be nested into each other (as we&#8217;ve seen for tabs &#8211; you can use tabbed layout and then in each tab &#8220;nest&#8221; any other type of layout).</p>
<p>It may seem to be a bit strict, that we shouldn&#8217;t just put the controls whatever we&#8217;d like to (as we are used to do in <em>WinForms</em>, for example <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;" /> ), but mobile development requires such restrictions.</p>
<p>Especially building for Android &#8211; as for September 2015, there were <strong>1.5 billion</strong> registered devices running Android system. This implies thousands of different screens resolutions, which must be handled by the UI of our apps.</p>
<p><span style="text-decoration: underline;"><strong>What types of Layouts do you use the most in your Android apps? Do you have any best practices using them ? Share your knowledge! <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/android-layout-types/">Android Layout Types</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/android-layout-types/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1695</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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MonayBack_ListOfPeople.png?fit=180%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_phoneDialerCall.png?fit=180%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_MainActivity.png?fit=180%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_PeopleActivity.png?fit=180%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/04/MoneyBack_IntentExtrasRetrieve.png?fit=300%2C155&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/ReSharper_Exc.png?fit=300%2C241&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/tests_rsharper.png?fit=300%2C63&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-23-31-44.png?fit=169%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_2017-03-25-21-23-07.png?fit=169%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/SQLiteNetFiles.png?fit=225%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson.png?fit=180%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_SavingPerson_Success.png?fit=180%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/countriesAndCitiesManager.png?fit=300%2C108&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/errorISONotFound.png?fit=300%2C136&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_attaching.png?fit=300%2C140&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_session_running.png?fit=300%2C44&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/addCity_Click-3.png?fit=300%2C107&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/dotTrace_GetSnapshot.png?fit=300%2C58&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_ThreadsTree.png?fit=300%2C138&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_LongestCall.png?fit=300%2C74&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/getAllEUCountriesList.png?fit=300%2C23&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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"><span class=pl-k>private</span> <span class=pl-smi>bool</span> <span class=pl-en>AddNewCity</span><span class=pl-kos>(</span><span class=pl-smi>string</span> <span class=pl-s1>cityName</span><span class=pl-kos>,</span> <span class=pl-smi>string</span> <span class=pl-s1>countryIso</span><span class=pl-kos>)</span></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"><span class=pl-kos>{</span></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">    <span class=pl-k>var</span> <span class=pl-s1>city</span> <span class=pl-c1>=</span> <span class=pl-s1>CountriesCitiesDbService</span><span class=pl-kos>.</span><span class=pl-en>GetNewCity</span><span class=pl-kos>(</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">    <span class=pl-k>var</span> <span class=pl-s1>country</span> <span class=pl-c1>=</span> <span class=pl-s1>EuropeanCountries</span><span class=pl-kos>.</span><span class=pl-en>FirstOrDefault</span><span class=pl-kos>(</span>ec <span class=pl-c1>=&gt;</span> <span class=pl-s1>ec</span><span class=pl-kos>.</span><span class=pl-s1>IsoCode</span><span class=pl-kos>.</span><span class=pl-en>Equals</span><span class=pl-kos>(</span><span class=pl-s1>countryIso</span><span class=pl-kos>)</span><span class=pl-kos>)</span><span class=pl-kos>;</span></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">    <span class=pl-c>// the rest of method&#39;s code&#8230;</span></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"><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/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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected1.png?fit=300%2C70&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/perfViewer_Corrected2.png?fit=300%2C65&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities.png?fit=300%2C150&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/diagram_backstack.png?fit=300%2C95&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/activities_states.png?fit=300%2C61&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_lifecycle_methods.png?fit=258%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/Screenshot_Lifecycle.png?fit=180%2C300&amp;ssl=1" 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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/android_sdk_size.png?fit=300%2C209&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/VS_Android_Xamarin_Solution.png?fit=195%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2017/03/MoneyBack_HelloWorld_Xamarin.png?fit=170%2C300&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/1.png?fit=300%2C29&amp;ssl=1" 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-medium-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2016/05/2.png?fit=300%2C29&amp;ssl=1" 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>
