Jekyll2021-07-04T21:49:35+00:00https://arghya.xyz/feed.xmlAC’s NotesTechnical & non-technical titbits of everyday programmer's life.Developer Posters and Stickers - designs2020-09-23T00:00:00+00:002020-09-23T00:00:00+00:00https://arghya.xyz/blog/developer-poster-and-stickers<h2 id="a-collection-of-developer--tech-related-designs">A collection of developer / tech related designs</h2>
<p>Here I’m sharing some basic poster / sticker designs which were not published before. These are mostly related to developer community, technology or programming swag. Most of them are very generic designs & could be printed as posters, t-shirts etc. Because of form factors, I think most of them are more appropriate for laptop stickers or coasters.</p>
<p class="notice--info"><strong>Note:</strong> There are some icons and logos used in some of the designs, they belong to their respective owners or communities. Also there are some quotes used, which are very common among software engineers and related communities, so do not belong to any particular person or entity.</p>
<h3 id="basic-coding-sticker-">Basic coding sticker 👩🏽💻👨🏼💻</h3>
<p>A basic sticker design with <code class="language-plaintext highlighter-rouge">VS Code</code> and <code class="language-plaintext highlighter-rouge">TypeScript</code> coding language logos. As we can see, this is just a graphic, so can be printed on any item and material of choice.</p>
<figure>
<a href="/images/blog/dev-stickers/vs-code-and-typescript-2-01.jpeg">
<img src="/images/blog/dev-stickers/vs-code-and-typescript-2-01.jpeg" alt="vs code and typescript" title="VS Code & TypeScript" />
</a>
<figcaption>VS Code & TypeScript</figcaption>
</figure>
<h3 id="developer-relatable-things-">Developer relatable things 💻</h3>
<p>Things developers say. Or they should. They are no joke!</p>
<figure class="third">
<a href="/images/blog/dev-stickers/testing-code-in-prod-01.jpeg">
<img src="/images/blog/dev-stickers/testing-code-in-prod-01.jpeg" alt="testing in production" title="Testing in production" />
</a>
<a href="/images/blog/dev-stickers/no-deploy-fridays-01.jpeg">
<img src="/images/blog/dev-stickers/no-deploy-fridays-01.jpeg" alt="no deploy fridays" title="No deploy Fridays" />
</a>
<a href="/images/blog/dev-stickers/im-not-free-01.jpg">
<img src="/images/blog/dev-stickers/im-not-free-01.jpg" alt="no i'm not free" title="I'm not free for 5 min" />
</a>
<figcaption>Dev: It works on my machine though!</figcaption>
</figure>
<h3 id="most-common-comments-in-code-">Most common comments in code 🙄</h3>
<figure class="third">
<a href="/images/blog/dev-stickers/to-do-01.jpeg">
<img src="/images/blog/dev-stickers/to-do-01.jpeg" alt="to do remove code" title="To do remove code" />
</a>
<a href="/images/blog/dev-stickers/to-do-7-01.jpeg">
<img src="/images/blog/dev-stickers/to-do-7-01.jpeg" alt="mutually blocking issues" title="TMutually blocking issues" />
</a>
<a href="/images/blog/dev-stickers/to-do-8-01.jpeg">
<img src="/images/blog/dev-stickers/to-do-8-01.jpeg" alt="that query though" title="That query though" />
</a>
<figcaption>TODO: Move to Antarctica before the world sees this code</figcaption>
</figure>
<h3 id="things-developers-say-️️">Things developers say 🙋🏾♂️🙋🏻♀️</h3>
<p>As developer, or people working with developers, you hear these things like each living day!</p>
<figure class="half">
<a href="/images/blog/dev-stickers/zoom-2-01.jpeg">
<img src="/images/blog/dev-stickers/zoom-2-01.jpeg" alt="sorry I was on mute" title="Zoom: Sorry, I was on mute!" />
</a>
<a href="/images/blog/dev-stickers/slack-1-01.jpeg">
<img src="/images/blog/dev-stickers/slack-1-01.jpeg" alt="let's grab beer sometime" title="Slack: Let's grab beer sometime" />
</a>
<a href="/images/blog/dev-stickers/zoom-1-01.jpeg">
<img src="/images/blog/dev-stickers/zoom-1-01.jpeg" alt="can you see my screen" title="Zoom: Can you see my screen?" />
</a>
<a href="/images/blog/dev-stickers/next-sprint-01.jpeg">
<img src="/images/blog/dev-stickers/next-sprint-01.jpeg" alt="we'll fix that in next sprint" title="We'll fix that in next sprint" />
</a>
<figcaption>How many times do you hear them everyday?</figcaption>
</figure>
<h3 id="everyday-programming-things-">Everyday programming things ↩</h3>
<ol>
<li><code class="language-plaintext highlighter-rouge">VS Code</code>, <code class="language-plaintext highlighter-rouge">Angular</code>, <code class="language-plaintext highlighter-rouge">RxJS</code>, <code class="language-plaintext highlighter-rouge">TypeScript</code></li>
<li><code class="language-plaintext highlighter-rouge">UiPath</code> Robot</li>
<li>Developer qualities</li>
<li><code class="language-plaintext highlighter-rouge">VS Code</code>, <code class="language-plaintext highlighter-rouge">Angular</code>, <code class="language-plaintext highlighter-rouge">RxJS</code>, <code class="language-plaintext highlighter-rouge">TypeScript</code> (again) with Yellow background</li>
</ol>
<figure class="half">
<a href="/images/blog/dev-stickers/vs-code-angular-rxjs-ts-01.jpeg">
<img src="/images/blog/dev-stickers/vs-code-angular-rxjs-ts-01.jpeg" alt="angular and related logos" title="Angular and related logos" />
</a>
<a href="/images/blog/dev-stickers/uipath-reboot-work-01.jpeg">
<img src="/images/blog/dev-stickers/uipath-reboot-work-01.jpeg" alt="uipth reboot work" title="UiPath Reboot Work" />
</a>
<a href="/images/blog/dev-stickers/coding-design-problem-solving-3-01.jpeg">
<img src="/images/blog/dev-stickers/coding-design-problem-solving-3-01.jpeg" alt="developer qualities" title="Developer qualities" />
</a>
<a href="/images/blog/dev-stickers/vs-code-angular-rxjs-ts-yellow-1-01.jpeg">
<img src="/images/blog/dev-stickers/vs-code-angular-rxjs-ts-yellow-1-01.jpeg" alt="angular and related logos" title="Angular and related logos in Yellow" />
</a>
<figcaption>Mixed theme stickers</figcaption>
</figure>
<blockquote>
<p>“I mean, you can have a different opinion on how to solve the problem! If you are sure, well, go ahead and do that.”</p>
</blockquote>
<figure>
<a href="/images/blog/dev-stickers/yes-that-too-4-01.jpeg">
<img src="/images/blog/dev-stickers/yes-that-too-4-01.jpeg" alt="random developer quote" title="Yes, you can do that too" />
</a>
<figcaption>Well, do it if you know already...</figcaption>
</figure>
<p>Full <del>stack</del> 🍔🍟☕ developer</p>
<figure>
<a href="/images/blog/dev-stickers/full-snack-developer-01.jpeg">
<img src="/images/blog/dev-stickers/full-snack-developer-01.jpeg" alt="full snack developer" title="Full snack developer" />
</a>
<figcaption>Full-stack developer is a myth</figcaption>
</figure>
<h3 id="rpa--robots-">RPA & Robots 🤖</h3>
<p>Few for the RPA (<code class="language-plaintext highlighter-rouge">Robotic Process Automation</code>) & <strong>UiPath</strong> community ❤</p>
<figure>
<a href="/images/blog/dev-stickers/building-bots-01.jpeg">
<img src="/images/blog/dev-stickers/building-bots-01.jpeg" alt="rbuilding bots" title="Building bots" />
</a>
<figcaption>Well, that's what RPA devs do for you</figcaption>
</figure>
<figure>
<a href="/images/blog/dev-stickers/uipath-robot-ai-01.jpeg">
<img src="/images/blog/dev-stickers/uipath-robot-ai-01.jpeg" alt="uipath robots & ai" title="UiPath robots & AI" />
</a>
<figcaption>UiPath Robots & AI is love</figcaption>
</figure>
<h2 id="notes">Notes</h2>
<p><strong>Tools:</strong> For all these designs I have used some standard tools like</p>
<ol>
<li>Adobe Spark</li>
<li>Microsoft Paint 😬</li>
<li>Google’s Snapseed</li>
</ol>
<p class="notice--warning"><strong>IMPORTANT NOTICE:</strong> All these poster / sticker designs are created by me, and belong to me. If you intend to use them in any context / capacity, please get in touch with me for watermark free high quality copies.</p>Some of my designs for developer or tech posters and stickersFoldable services architecture2020-05-23T00:00:00+00:002020-05-23T00:00:00+00:00https://arghya.xyz/articles/foldable-services-architecture<h1 id="foldable-micro-services">Foldable micro-services</h1>
<p>In this short article I’ll describe an <em>approach for building a set of services, which can be deployed as separate services, or a single service with multiple end-points, without any major change in code</em>.</p>
<p>Though I have said <em>“micro-services”</em> in the heading, it does not have anything to do with the <em>“standard notion of microservices”</em>, rather it simply means a bunch of lean services which can exist on their own, without necessarily depending on the other services. So, that can be like the standard type of <code class="language-plaintext highlighter-rouge">microservices</code>, or just <code class="language-plaintext highlighter-rouge">SOA</code> done the right way (not heavy, multi-fucntional, monolithic services) or just any type of <code class="language-plaintext highlighter-rouge">web services</code>.</p>
<p>We can say this is a <code class="language-plaintext highlighter-rouge">design pattern</code>, but I’d rather think of this just as a design idea, that applies to a very specific use case, as described below.</p>
<blockquote>
<p>I need to build a set of independent web services. I want deployment flexibility. I may want to deploy them as independent services on separate servers/containers. Or in some cases, I’d want to deploy them as a single set of services, deployed as a single deployment unit. And between this move, I do not want a major code change. When deployed as single service, we’d want inter-service calls to be direct function calls rather that API calls, for performance & resources!</p>
</blockquote>
<p>Following is a design approach for the problem statement above that worked for us, and I guess it might help others as well.</p>
<p class="notice--info"><strong>Note:</strong> This pattern applies ONLY to the scenario described above, and it is NOT a generic micro-services pattern! Do NOT follow this pattern if your scenario/need is different. This comes with a few constraints, one being coupling to a single programming language/platform. If you want to build separate services on different <em>“programming stacks”</em>, this will not work.</p>
<h2 id="foldable-services-architecture---rationale">Foldable services architecture - Rationale</h2>
<p>This is what we want from our services</p>
<ul>
<li>In the long term, we want to deploy the web services on cloud/containers</li>
<li>The services should be able to talk to each other, and expose some public APIs (one or more per service), for client applications to talk to</li>
<li>We’d want to deploy the services as bunch of lean/micro services, behind an API Gateway, with some public Auth integrated</li>
<li>But for some customers, we may also want to deploy everything locally behind a single local web server</li>
<li>For local deployment, we do not want to get into the complexity of multiple services, containers, api gateway, inter-service auth, service orchestration etc.</li>
<li>In the move from local client to cloud, we want full reuse of code, with least amount of throw-away code</li>
<li>While in local client, for simplicity & performance, we’d want inter-service communication as plain function calls across DLLs (rather than web service calls)</li>
<li>In cloud deployment, those inter-service calls will become HTTP based API calls. This should not affect the external APIs exposed for clients to use</li>
</ul>
<h2 id="common-standard--structure">Common standard & structure</h2>
<ul>
<li>All the services are implemented in the same language/platform/<em>“stack”</em> (e.g. <code class="language-plaintext highlighter-rouge">JVM</code> or <code class="language-plaintext highlighter-rouge">.NET Core</code>)</li>
<li>Each service is a separate solution/deployable (with one or more projects/modules)</li>
<li>All the service solutions are part of one bigger solution
<ul>
<li>Easier code sharing with common projects</li>
<li>Easy to expose all service APIs together (single deployment)</li>
<li>For common models, there should be <code class="language-plaintext highlighter-rouge">shared models</code> (e.g. <code class="language-plaintext highlighter-rouge">POJO</code>/<code class="language-plaintext highlighter-rouge">POCO</code>)</li>
</ul>
</li>
<li>All public API definitions are defined in a common <code class="language-plaintext highlighter-rouge">API Contracts</code> layer/project
<ul>
<li>All services/projects can refer to the API Contracts project</li>
<li>API Contracts project refers ONLY to the shared models project</li>
<li>If required, some domain agnostic projects like <code class="language-plaintext highlighter-rouge">Utilities</code>, <code class="language-plaintext highlighter-rouge">Data Access</code> can also be shared</li>
</ul>
</li>
<li>The API end-points
<ul>
<li>There is an <code class="language-plaintext highlighter-rouge">API Functions</code> layer that actually implements the API Contracts in full, i.e. no additional code is required to achieve the required API functionalities beyond this, as defined by the contracts</li>
<li>Above that, there’d be a very thin <code class="language-plaintext highlighter-rouge">API Layer</code> which will simply expose the API Functions as network callable API end-points. In <code class="language-plaintext highlighter-rouge">MVC</code> world, those can be bunch of simple <code class="language-plaintext highlighter-rouge">Controllers</code></li>
<li>The Controllers can have security, auth, caching etc. API functionalities plugged in, but there should be 0 (zero) application/domain logic</li>
</ul>
</li>
<li>In the move from single-client-app to distributed cloud deployment, nothing changes for the front-end or client apps. It still calls the same HTTP based APIs, with exact same contracts. Only the base URL will change from local URL to public API Gateway URLs</li>
<li>For public APIs, ideally <code class="language-plaintext highlighter-rouge">AuthN/AuthZ</code> should be implemented between client & services</li>
</ul>
<h2 id="design-01-single-deployment-unit">Design 01: Single deployment unit</h2>
<ul>
<li>All services are installed locally behind a single web server</li>
<li>All the service APIs are exposed as a single set of APIs</li>
<li>Inter-service calls are fulfilled through direct function calls</li>
<li>NOTE: Here, the bigger outer solution is deployed as one unit</li>
<li>There is a single copy of binaries for all the common modules like Shared Models, API Contracts</li>
<li>That also means <code class="language-plaintext highlighter-rouge">IoC/DI</code> resolves contracts across the bigger solution</li>
<li>Please note, the generic structure of service core shown on the bottom-left is not absolute. It just means that the service core can have their own internal layers for separation of concern, maintainability, testability etc.</li>
</ul>
<p><img src="/images/posts/services/FoldableServices_1.jpg" alt="Image" /></p>
<p class="notice--info"><strong>Note:</strong> Why should the <code class="language-plaintext highlighter-rouge">API Facade</code> or <code class="language-plaintext highlighter-rouge">API Layer</code> (below) should implement <code class="language-plaintext highlighter-rouge">API Contracts</code>, when <code class="language-plaintext highlighter-rouge">API Functions</code> already implements them? Well, the functions layer actually implements the functionalities defined in the contracts. The upper layers (facade & API layer), doesn’t necessarily need to implement the contracts. The only reason this is recommended is, so that there is never a discrepency between the functions & API layer. They should always have the exact same <em>“shape”</em> (function signatures), and the above layer should directly expose the functions layer without ANY extra code, except infrastructure related ones.</p>
<h3 id="design-02-distributed-deployment">Design 02: Distributed deployment</h3>
<ul>
<li>All services are installed on cloud, clients access them over internet</li>
<li>All the services are deployed as independent lean/micro services</li>
<li>Inter-service calls are fulfilled through API calls</li>
<li>NOTE: Here each (inner) service solution is deployed separately
<ul>
<li>There is a separate copy of binaries for the common modules like Shared Models, API Contracts, for each service installation</li>
<li>That also means <code class="language-plaintext highlighter-rouge">IoC/DI</code> resolves contracts only within each service project</li>
</ul>
</li>
<li>Here, the <code class="language-plaintext highlighter-rouge">API Facade</code> layer is discarded, and each service gets it’s own <code class="language-plaintext highlighter-rouge">API Layer</code></li>
<li>And there is a <code class="language-plaintext highlighter-rouge">Network Layer</code> in each service that basically implements the API Contracts from other services (ONLY the required parts), through HTTP calls to the actual service APIs. This layer is OPTIONAL i.e. only used if the specific service needs to communicate with other service(s)</li>
</ul>
<p><img src="/images/posts/services/FoldableServices_2.jpg" alt="Image" /></p>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Possible bunch of <code class="language-plaintext highlighter-rouge">NotImplemented</code> methods in <code class="language-plaintext highlighter-rouge">Layer 3</code></li>
<li>Works only if the whole system is written in same language or targetting a single platform/intermediate language</li>
<li>There still is small layer of code that is not re-used in both deployments (e.g. API Facade)</li>
<li>Overly complex if single deployment unit is not a requirement (but, that is the whole point of the article)</li>
</ul>A simple software service architecture to create services that can be scaled out separately, or be run as a single deployment unitWebAssembly - What it is & Why is it so important2020-02-29T00:00:00+00:002020-02-29T00:00:00+00:00https://arghya.xyz/articles/webassembly-wasm-wasi<p>If you are a web developer, or a software developer in general, you must have heard of something called <code class="language-plaintext highlighter-rouge">WebAssembly</code> in last few years. If you did, but do not actually know what it is, and why you keep hearing about them - this post is for you. If you are already compiling your code into <code class="language-plaintext highlighter-rouge">wasm</code> and loading them into your <code class="language-plaintext highlighter-rouge">JavaScript</code> code, then you can happily skip.</p>
<p>If you’re in the first group, jump right in. Here, we’ll try to understand what is <code class="language-plaintext highlighter-rouge">WebAssembly</code>, what is the context of it, the hype vs. the fact, and a bit of the future. You might have already come across bunch of articles, blog posts, tweets, videos & even conference talks about it, but still probably have no clue what it is? Is it a new tool, a design pattern or a shiny new JavaScript framework?</p>
<h2 id="what-is-webassembly">What is <em>WebAssembly</em></h2>
<blockquote>
<p>WebAssembly is a new, low level binary code, for the web!</p>
</blockquote>
<p><em>Wait, a what?</em></p>
<p>That’s right! That’s what <code class="language-plaintext highlighter-rouge">WebAssembly</code> is. Let us take this definition apart, and understand piece-by-piece
<img src="/images/posts/webassembly/Web_Assembly.png" alt="image-right" class="pull-right" /></p>
<ul>
<li>It’s a <code class="language-plaintext highlighter-rouge">new language</code>. It became the offical <em><strong>“fourth language for web”</strong></em> on <a href="https://www.w3.org/2019/12/pressrelease-wasm-rec.html.en">5th December 2019</a>, i.e. after HTML, CSS & JavaScript</li>
<li>It’s <code class="language-plaintext highlighter-rouge">binary</code>, so it is not really human readable (it’s an <em>“assembly”</em> language for the web)</li>
<li>It’s <code class="language-plaintext highlighter-rouge">low level</code>, i.e. it’s much closer to actual machine code (than <code class="language-plaintext highlighter-rouge">JavaScript</code> and other higher level languages)</li>
<li>And it’s <code class="language-plaintext highlighter-rouge">for the web</code>, that means (modern) web browsers can read and execute them</li>
</ul>
<h3 id="so-how-do-i-code-in-webassembly">So, how do I code in <code class="language-plaintext highlighter-rouge">WebAssembly</code>?</h3>
<p>Actual WebAssembly is a binary language. Though there is a <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format">text representation</a>, you as a developer won’t generally <em>“write”</em> code in <code class="language-plaintext highlighter-rouge">WebAssembly</code>! <strong>It’s actually an <code class="language-plaintext highlighter-rouge">IR</code> or <code class="language-plaintext highlighter-rouge">Intermediate Representation</code></strong> code, comparable to <code class="language-plaintext highlighter-rouge">ByteCode</code> in <code class="language-plaintext highlighter-rouge">Java</code> or <code class="language-plaintext highlighter-rouge">MSIL/CIL</code> in <code class="language-plaintext highlighter-rouge">.NET</code>. It’s meant to be a compilation target for higher level languages.</p>
<p>Basically it’s a set of low level binary instructions that works across common standard hardware. Unlike higher level languages like <code class="language-plaintext highlighter-rouge">C#</code>, <code class="language-plaintext highlighter-rouge">Go</code> or <code class="language-plaintext highlighter-rouge">Java</code>, it is more closer to machine language, and can be converted into actual <code class="language-plaintext highlighter-rouge">machine code</code> very fast & efficiently. So rather than writing code in it, you still write code in a language that you already know, like <code class="language-plaintext highlighter-rouge">C/C++</code> or <code class="language-plaintext highlighter-rouge">Rust</code>, and a special compiler compiles your code into <code class="language-plaintext highlighter-rouge">WebAssembly</code>, and that runs inside a special <code class="language-plaintext highlighter-rouge">Virtual Machine</code>. This <code class="language-plaintext highlighter-rouge">VM</code> can turn the <code class="language-plaintext highlighter-rouge">IR</code> into actual, platform specific <code class="language-plaintext highlighter-rouge">Machine Code</code> and execute them. This <code class="language-plaintext highlighter-rouge">VM</code> can run on any type of platform (hardware + OS).</p>
<p><img src="/images/posts/webassembly/WebAssembly_compile.png" alt="Image" /></p>
<p>In a nutshell, that’s like the main idea behind WebAssembly, to be able to <em><strong>run pre-compiled code, written in any language, on the web!</strong></em></p>
<p>Okay, but why?</p>
<h3 id="why-webassembly">Why <code class="language-plaintext highlighter-rouge">WebAssembly</code>?</h3>
<p>I cannot read or write code in WebAssembly! Then what is the purpose of it? Why have it as the <em>fouth language for the web</em>? We already have our good ol’ <code class="language-plaintext highlighter-rouge">JavaScript</code>!</p>
<p>Yes, <code class="language-plaintext highlighter-rouge">JavaScript</code> works, and it works pretty well. And there are really cool <code class="language-plaintext highlighter-rouge">JS Frameworks</code> like <code class="language-plaintext highlighter-rouge">Angular</code>, <code class="language-plaintext highlighter-rouge">React</code>, <code class="language-plaintext highlighter-rouge">Vue</code> etc. that make complex web development much easier. In fact <code class="language-plaintext highlighter-rouge">JS</code> is so cool, that now lot of people even write back-end or server-side code in <code class="language-plaintext highlighter-rouge">JS</code>, thanks to <code class="language-plaintext highlighter-rouge">Node</code>!</p>
<p>BUT, there are issues with <code class="language-plaintext highlighter-rouge">JavaScript</code>, mainly with <strong><code class="language-plaintext highlighter-rouge">performance</code></strong>! It works fine for a standard web applications where small pieces of processing is done on the web, based on user interaction. Generally, the heavy processing is done on servers, and web interacts with them through <code class="language-plaintext highlighter-rouge">http</code> services. But it does not work well when lot of real-time processing is required, think of - image & video processing, 3D gaming, AR/VR etc.</p>
<p class="notice--success"><strong>NOTE:</strong> JavaScript is an interpreted language i.e. at the run-time, each line of code is turned into machine code as it is encountered. This happens everytime, even the same line of code is executed multiple times (e.g. loops). This is inefficient. And there is no way to look at the whole code at once & ompimize. Also, the garbage collector cycles take it’s time to run and free up memory, stalling the applications. Well, this is how JavaScript used to run traditionally. But the modern JavaScript engines use <code class="language-plaintext highlighter-rouge">JIT compiler</code> which partially compiles the code & has some performance improvements. But still it’s not the best we could get, partly because of the <code class="language-plaintext highlighter-rouge">dynamic</code> nature of JavaScript. Learn more about them in this <a href="https://hacks.mozilla.org/category/code-cartoons/a-cartoon-intro-to-webassembly/">series of posts by Lin Clark</a>.</p>
<p>Web has been an important medium of user interaction for software programs, and with modern SaaS & cloud applications, users are now enabled to do more & more stuffs on web. Users & developers, both want to be able to do more stuffs on web, and faster. And with frameworks like <code class="language-plaintext highlighter-rouge">Electron</code>, web apps can run like native apps on desktop, cross-platform. Now, apart from <code class="language-plaintext highlighter-rouge">JavaScript</code> being not-so-fast, always going over the network for any heavy processing & bringing back results, makes fast processing on web applications almost impossible.</p>
<p><code class="language-plaintext highlighter-rouge">WebAssembly</code> aims to solve this problem. WebAssembly is a new type of assembly language (Intermediate Code) that</p>
<ol>
<li>Any language compiler can target</li>
<li>Can be executed on web, stand-alone</li>
</ol>
<p>With that, developers can write their code on high-performance languages like <code class="language-plaintext highlighter-rouge">C/C++</code> or <code class="language-plaintext highlighter-rouge">Rust</code> and compile them into <code class="language-plaintext highlighter-rouge">WebAssembly</code>. This <code class="language-plaintext highlighter-rouge">IR</code> code matches very closely with machine languages across hardwares. Now the browser (with <code class="language-plaintext highlighter-rouge">WebAssembly VM</code>s) can directly translate that into machine code & execute. This can make the code run real fast in near native (directly running compiled machine code) speed.</p>
<p class="notice--info"><strong>Important:</strong> For this to happen, 2 things are required. [1] Different languages need to compile into WebAssembly [2] Browsers need to be ready to run WebAssembly. For <em>#1</em>, different languages need to come up with new compilers that target WebAssembly rather than their standard IR. This is already available for <code class="language-plaintext highlighter-rouge">C/C++</code>, <code class="language-plaintext highlighter-rouge">Rust</code> and even <code class="language-plaintext highlighter-rouge">C#</code>. And very soon we’ll have compilers for many other langues, some of them might be ready by the time you read this. And <em>#2</em> is not an issue, as all the modern brosers already support WebAssembly viz. <code class="language-plaintext highlighter-rouge">Firefox</code>, <code class="language-plaintext highlighter-rouge">Chrome</code>, <code class="language-plaintext highlighter-rouge">Edge</code> & <code class="language-plaintext highlighter-rouge">Safari</code>. In fact, WebAssembly is a joint effort by <code class="language-plaintext highlighter-rouge">W3C</code>, <code class="language-plaintext highlighter-rouge">Mozilla</code>, <code class="language-plaintext highlighter-rouge">Google</code>, <code class="language-plaintext highlighter-rouge">Microsoft</code> & <code class="language-plaintext highlighter-rouge">Apple</code> (and of course community members). So, all the major browsers should always be up to date with latest WebAssembly standards.</p>
<p><img src="/images/posts/webassembly/wasm-browsers.png" alt="Image" /></p>
<h2 id="points-to-remember">Points to remember</h2>
<p>Now that we know what is WebAssembly and what problem it aims to solve, let’s look at a bunch of important points to note.</p>
<ol>
<li><code class="language-plaintext highlighter-rouge">WebAssembly</code> is still a <strong>new & evolving</strong> technology. Things are changing very fast, and by the time you read, many things might have changed</li>
<li>It’s a <strong>low level binary code</strong>, meant to be <strong>target of compilation</strong> for higher level (ideally fast) languages. Any language that wants to generate <code class="language-plaintext highlighter-rouge">WebAssembly</code>, needs to come up with a compiler that compiles from that language to <code class="language-plaintext highlighter-rouge">WebAssembly</code> IR</li>
<li>As a language, it’s <strong>strongly typed</strong> (unlike <code class="language-plaintext highlighter-rouge">JavaScript</code>)</li>
<li>It <strong>runs inside a <code class="language-plaintext highlighter-rouge">VM</code></strong> (like <code class="language-plaintext highlighter-rouge">Java</code> runs indside <code class="language-plaintext highlighter-rouge">JVM</code> or <code class="language-plaintext highlighter-rouge">C#</code> runs inside <code class="language-plaintext highlighter-rouge">.NET CLR</code>). The <code class="language-plaintext highlighter-rouge">WebAssembly Virtual Machine</code> works like a <strong>Stack Machine</strong> i.e. all opeations work on the stack. For each operation, it <code class="language-plaintext highlighter-rouge">push</code> or <code class="language-plaintext highlighter-rouge">pop</code> something on the internal memory stack (e.g. a functions pops operands from the stack, and at the end, the return value is pushed on top of stack)</li>
<li><code class="language-plaintext highlighter-rouge">WebAssembly</code> is frequently abbreviated as <code class="language-plaintext highlighter-rouge">WA</code> or <strong><code class="language-plaintext highlighter-rouge">wasm</code></strong>. Actual WebAssembly files also have <code class="language-plaintext highlighter-rouge">*.wasm</code> extension</li>
<li>Generally the binary size is pretty <strong>small</strong> (compared to <code class="language-plaintext highlighter-rouge">JavaScript</code>, even when compressed) & <strong>executes fast</strong> because of it’s near native model</li>
<li>On browser, <code class="language-plaintext highlighter-rouge">WebAssembly</code> runs with same priviledges as <code class="language-plaintext highlighter-rouge">JavaScript</code> code, so it has the same <strong>security</strong> levels of current browser code (e.g. it cannot start manipulating files on client system, without explicit user action)</li>
<li>It’s <strong>portable & platform agnostic</strong>, i.e. indepndent of underlying <code class="language-plaintext highlighter-rouge">hardware</code> or <code class="language-plaintext highlighter-rouge">OS</code></li>
<li>There is a <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format">text representation</a> of <code class="language-plaintext highlighter-rouge">wasm</code>, that is human readable and follows <code class="language-plaintext highlighter-rouge">s-expressions</code> format. Though it’s totally possible to write code in <code class="language-plaintext highlighter-rouge">WAT</code>, the main idea behind this is to enable <code class="language-plaintext highlighter-rouge">debug</code> WebAssembly code at run-time (it’s not ready though)</li>
<li><code class="language-plaintext highlighter-rouge">WebAssembly</code> enables web browsers to run code written in other languages than <code class="language-plaintext highlighter-rouge">JavaScript</code>. <code class="language-plaintext highlighter-rouge">C/C++</code> and <code class="language-plaintext highlighter-rouge">Rust</code> were supported from the beginning. <code class="language-plaintext highlighter-rouge">.NET</code> already supports it through <a href="https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor">Blazor</a>, and support for many other languages should be available soon</li>
<li>Some popular compilers for <code class="language-plaintext highlighter-rouge">WebAssembly</code> are <a href="https://v8.dev/blog/emscripten-llvm-wasm">LLVM & Emscripten</a>. Currently <strong>Emscripten</strong> is the most popular compiler</li>
<li>To get the taste of first-hand <code class="language-plaintext highlighter-rouge">wasm</code> development, follow this <strong><a href="https://webassembly.org/getting-started/developers-guide/">Hello World</a> tutorial</strong></li>
</ol>
<h3 id="why-wasm-is-great">Why <code class="language-plaintext highlighter-rouge">Wasm</code> is great</h3>
<ol>
<li>Can have much <em><strong>higher performance</strong></em> than JavaScript
<ol>
<li>Smaller download size, mainly for the binary format</li>
<li>As code is already in IR (Intermediate Representation) code, it is much closer to machine code. So the whole code can be translated to stable machine code quickly rather than the optimize & re-optimize cycles of JS JIT compiler (also because the types are static)</li>
<li>No Garbage Collection by design, so <code class="language-plaintext highlighter-rouge">GC</code> cycles are saved</li>
</ol>
</li>
<li><em><strong>Code sharing</strong></em>
<ol>
<li>It provides a simple and performant way of sharing <code class="language-plaintext highlighter-rouge">pre-compiled</code> (<code class="language-plaintext highlighter-rouge">wasm</code> as IR is close to machine code) code across platforms, written in <code class="language-plaintext highlighter-rouge">different languages</code></li>
<li>Same <code class="language-plaintext highlighter-rouge">wasm</code> code can run in front-end as well as in the back-end, like standard server side code. So basically, code sharing between front-end & back-end. <strong>Note</strong> that it’s already possible with <code class="language-plaintext highlighter-rouge">JavaScript</code> & <code class="language-plaintext highlighter-rouge">Nodejs</code>, but that doesn’t provide speed of lower level languages like <code class="language-plaintext highlighter-rouge">C/C++</code></li>
</ol>
</li>
<li>Different <code class="language-plaintext highlighter-rouge">wasm</code> modules, written in different languages, can interoperate easily, making it very easy to collaborate between developers from different backgrounds and <em><strong>interoperate otherwise incompatible modules</strong></em> (this will become possible with implementation of <a href="https://www.youtube.com/watch?time_continue=12&v=Qn_4F3foB3Q&feature=emb_logo">interface types</a>)
<img src="/images/posts/webassembly/wasm-js-2.png" alt="image-right" class="pull-right" /></li>
<li>Works seamlessly with <code class="language-plaintext highlighter-rouge">JavaSCript</code> i.e. <code class="language-plaintext highlighter-rouge">wasm</code> & <code class="language-plaintext highlighter-rouge">JavaScript</code> can exchange data and call each other. In fact, currently <code class="language-plaintext highlighter-rouge">wasm</code> cannot be run without <code class="language-plaintext highlighter-rouge">JS</code> becuase [1] It needs <code class="language-plaintext highlighter-rouge">JS</code> to load the <code class="language-plaintext highlighter-rouge">wasm</code> module [2] <code class="language-plaintext highlighter-rouge">DOM</code> manipulation happens through <code class="language-plaintext highlighter-rouge">JS</code> only</li>
<li>With <code class="language-plaintext highlighter-rouge">wasm</code> we can truly relize <em><strong>serverless web applications</strong></em>, that can actually run without any backing servers (it can do heavy computations, connect to database and what not!)</li>
<li>Can also <em><strong>run outside browser</strong></em>, in a safe & fast manner. <code class="language-plaintext highlighter-rouge">Wasm</code> provides a <a href="https://hacks.mozilla.org/2019/03/standardizing-wasi-a-webassembly-system-interface/">light-weight sandboxing</a> by default. More about this later</li>
</ol>
<h3 id="whats-not-so-great-yet">What’s not-so-great (yet)</h3>
<ol>
<li>Not complete, or <em>“ready”</em> yet. Many features are still under development or in proposal stage</li>
<li>Compilation and loading process is bit complex, and apparently no official integration into popular build tools like webpack or Angular CLI (this may change soon though)</li>
<li>By design, code needs to be compiled before distribution. So, <em>fix JS directly on CDN</em> kind of approach does not work</li>
<li><code class="language-plaintext highlighter-rouge">Internet Explorer</code> and older versions of other browsers does not support</li>
<li>Some conventions of <code class="language-plaintext highlighter-rouge">wasm</code> makes it more complex for developers to write code. So, high level language compilers need to provide some extra layer for developers to code easily. For example
<ol>
<li><code class="language-plaintext highlighter-rouge">Wasm</code> <em><strong>supports only numbers as method parameters</strong></em>. To use any other types, one needs to work with memory locations / pointers directly (will be easier with the <a href="https://hacks.mozilla.org/2019/08/webassembly-interface-types/">interface types</a> implementation)</li>
<li>No automatic <code class="language-plaintext highlighter-rouge">GC</code>. Memory has to be managed manually</li>
</ol>
</li>
<li>Because of current not-so-optimized wasm invocation from <code class="language-plaintext highlighter-rouge">JS</code>, it doesn’t perform well if there are lot of small functions to be invoked (lot of jumping between <code class="language-plaintext highlighter-rouge">JS</code> and <code class="language-plaintext highlighter-rouge">wasm</code>)</li>
<li><code class="language-plaintext highlighter-rouge">WebAssembly</code>, in the current form, <em><strong>cannot directly manipulate DOM</strong></em>. No direct access to the Web APIs. For that, it needs to go through <code class="language-plaintext highlighter-rouge">JavaScript</code>. Even for loading <code class="language-plaintext highlighter-rouge">wasm</code> modules, it has to depend on <code class="language-plaintext highlighter-rouge">JS</code></li>
<li>Not really debuggable for high-level language source code (should change in future with source-maps)</li>
<li>No fully featured <em><strong>multi-threading support</strong></em></li>
</ol>
<p class="notice--success"><strong>NOTE:</strong> As WebAssembly is just in the early stage of development, specs proposals & implementations change fast. Many of the limitations mentioned above might not apply in future. And that may happen pretty soon.</p>
<h2 id="wasi---run-webassembly-everywhere"><code class="language-plaintext highlighter-rouge">WASI</code> - run <code class="language-plaintext highlighter-rouge">WebAssembly</code> everywhere</h2>
<p>If we think about about the core working principles of <code class="language-plaintext highlighter-rouge">WebAssembly</code>, it’s not difficult to visualize <code class="language-plaintext highlighter-rouge">wasm</code> executing outside web browsers as well! Provided the <code class="language-plaintext highlighter-rouge">WebAssembly Virtual Machine</code> is available, <code class="language-plaintext highlighter-rouge">wasm</code> code can run in any system on any platform, browser or not!</p>
<p>Developers are already running <code class="language-plaintext highlighter-rouge">wasm</code> outside browsers for the amazing benefits it provides - fast, scalable, secure way to run the same code across all machines.</p>
<p>Now the wasm committee is also pushing the idea, and working to provide a standard set of interfaces so that - <code class="language-plaintext highlighter-rouge">wasm</code> applications written in different languages can run acorss platforms, talk to each-other seamlessly, can access necessary system APIs & execute securely inside a sandbox (with controlled access, memory, network, filesystem etc). Thasts <strong><code class="language-plaintext highlighter-rouge">WebAssembly System Interface</code></strong> or <em><strong>WASI</strong></em>. Read <a href="https://hacks.mozilla.org/2019/03/standardizing-wasi-a-webassembly-system-interface/">this</a> for more details.</p>
<p>Now think of the implications. <code class="language-plaintext highlighter-rouge">WASI</code>, if works as expected, will open up crazy new ways of writing applications - on any language, that runs everywhere, and talk to each other fluently without any wrappers or network calls!</p>
<p>When <code class="language-plaintext highlighter-rouge">WASI</code> was proposed, <strong><code class="language-plaintext highlighter-rouge">Docker</code></strong> co-founder & CTO <a href="https://twitter.com/solomonstre">Solomon Hykes</a> tweeted, if <code class="language-plaintext highlighter-rouge">WASI</code> was already available, <code class="language-plaintext highlighter-rouge">Docker</code> wouldn’t have been necessary!</p>
<p>Take a moment. Or two. And think about that! 🤯</p>
<blockquote class="twitter-tweet tw-align-center"><p lang="en" dir="ltr">If WASM+WASI existed in 2008, we wouldn't have needed to created Docker. That's how important it is. Webassembly on the server is the future of computing. A standardized system interface was the missing link. Let's hope WASI is up to the task! <a href="https://t.co/wnXQg4kwa4">https://t.co/wnXQg4kwa4</a></p>— Solomon Hykes (@solomonstre) <a href="https://twitter.com/solomonstre/status/1111004913222324225?ref_src=twsrc%5Etfw">March 27, 2019</a></blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<h2 id="a-few-finals-notes">A few finals notes</h2>
<ul>
<li>When can I start using <code class="language-plaintext highlighter-rouge">wasm</code>? Right now! Though it’ll change a lot in future, it’s already available to use and it really works!</li>
<li>Will it replace <code class="language-plaintext highlighter-rouge">JavaScript</code>? No. At least not any time soon. Currently <code class="language-plaintext highlighter-rouge">wasm</code> depends on <code class="language-plaintext highlighter-rouge">JS</code> for loading & any kind of <code class="language-plaintext highlighter-rouge">DOM</code> manipulation. Though it’ll change in future, <code class="language-plaintext highlighter-rouge">JS</code> is already huge and has it’s own high place in web development. Practically, it’s the only language tailored fit for web development, other languages - not really. All the amazing JS frameworks also make it almost irreplacable. So, probably no existing <code class="language-plaintext highlighter-rouge">JS</code> based web applications will be re-written in <code class="language-plaintext highlighter-rouge">wasm</code>, but a time might come when new web applications might be written completely in <code class="language-plaintext highlighter-rouge">wasm</code> (in a language like <code class="language-plaintext highlighter-rouge">C++</code>, <code class="language-plaintext highlighter-rouge">Go</code>, <code class="language-plaintext highlighter-rouge">Kotlin</code> or something that doesn’t even exist today)!</li>
<li>Why not re-write all the web apps in WebAssembly? For typical web apps, where it’s the app that’s waiting for user most of the time, and needs to talk to a remote database to get data, <code class="language-plaintext highlighter-rouge">wasm</code> will not provide much performance gain. So all the development, testing, integration effort will not be worth it.</li>
<li>What about <code class="language-plaintext highlighter-rouge">Docker</code>? Will <code class="language-plaintext highlighter-rouge">wasm</code> replace it? <em>“No, but imagine a future where Docker runs linux containers, windows containers and wasm containers side by side. Over time wasm might become the most popular container type. Docker will love them all equally, and run it all :)”</em> - <a href="https://twitter.com/solomonstre/status/1111113329647325185?s=20">Solomon Hykes</a></li>
<li>Ok, so what about <code class="language-plaintext highlighter-rouge">JS developers</code>? Is it like all the JS developers will now have to learn a completely new language (maybe more than one?) just to keep up with web development? Well, learning a new language might be really helpful, mainly to benefit from the performance of lower level languages. But it may not be necessary. For instance, there is already a popular language <strong><a href="https://github.com/AssemblyScript/assemblyscript">AssemblyScript</a></strong> that can compile <code class="language-plaintext highlighter-rouge">TypeScript</code> (a subset actually) into <code class="language-plaintext highlighter-rouge">WebAssembly</code>.</li>
<li>So, now we’ll see back-end developers start doing front-end development? Not very soon probably. But it will happen definitely. With the advent of <code class="language-plaintext highlighter-rouge">Nodejs</code>, we saw front-end developers become <em>“full-stack”</em> developers. Once wasm gets more stable (and DOM access), we may see the <em><strong>reverse trend</strong></em> of typical back-end developers becoming <em>“full-stack”</em> developers! But front-end development requires some specific expertise (DOM, HTML, CSS etc.) & a different programming paradigm, which only comes with time.</li>
</ul>
<p class="notice--warning"><strong>Disclaimer:</strong> I’m by no means a WebAssembly expert. I’m just a developer interested in the development & future applications of WebAssembly. My whole source of knowledge was my research on wasm, to see if it could solve a specific problem that I was not able to solve with current web technologies. Though I figured out that wasm, in it’s current state, cannot solve the problem, but all the amazing articles and talks (few mentioned in references below) got me really excited about WebAssembly and all the new possibilities it opens up! 😄</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://webassembly.org/">The WebAssembly home page</a></li>
<li><a href="https://github.com/WebAssembly">GitHub repos</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/WebAssembly">Mozilla WebAssembly docs</a></li>
<li><a href="https://hacks.mozilla.org/category/code-cartoons/a-cartoon-intro-to-webassembly/">A cartoon intro to WebAssembly</a></li>
<li><a href="https://webassembly.org/getting-started/developers-guide/">Wasm Hello World guide</a></li>
<li>Tools
<ul>
<li><a href="http://mbebenita.github.io/WasmExplorer/">WasmExplorer</a></li>
<li><a href="https://webassembly.studio/">WebAssemblyStudio</a></li>
<li><a href="https://emscripten.org/">Emscripten</a></li>
</ul>
</li>
<li><a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format">Wasm Text Format WAT</a></li>
<li><a href="https://hacks.mozilla.org/2019/03/standardizing-wasi-a-webassembly-system-interface/">WASI</a></li>
<li><a href="https://github.com/AssemblyScript/assemblyscript">AssemblyScript</a></li>
<li>Videos
<ul>
<li><a href="https://www.youtube.com/watch?v=6Y3W94_8scw">WebAssembly Demystified - Jay Phelps</a></li>
<li><a href="https://www.youtube.com/watch?v=fh9WXPu0hw8">Bringing WebAssembly outside the web with WASI by Lin Clark</a></li>
<li><a href="https://www.youtube.com/watch?time_continue=12&v=Qn_4F3foB3Q&feature=emb_logo">Interface Types - Lin Clark</a></li>
</ul>
</li>
<li>Also look at this <a href="https://github.com/WebAssembly/design/issues/112">WebAssembly logo contest</a> from 2015, just for fun</li>
</ul>The what, why, how & when of WebAssembly for the dummiesThe great new Windows 10 Terminal2019-06-27T00:00:00+00:002019-06-27T00:00:00+00:00https://arghya.xyz/articles/new-windows-terminal<h2 id="the-new-windows-terminal">The new <em>Windows Terminal</em></h2>
<p>Now the preview version for Windows 10 terminal is available to <a href="https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701?activetab=pivot:overviewtab">download</a> from Microsoft store. You could also build it from the source code on <a href="https://github.com/microsoft/terminal">GitHub</a>.</p>
<p>So, what’s this? And why would you care?</p>
<p>This is like a whole new version of the classic <code class="language-plaintext highlighter-rouge">Command Prompt</code> command-line terminal on Windows, which is super cool, open source & comes with bunch of really helpful productivity features. If you are a developer, love/need to use multiple command line applications (e.g. <code class="language-plaintext highlighter-rouge">cmd</code>, <code class="language-plaintext highlighter-rouge">PowerShell</code>, <code class="language-plaintext highlighter-rouge">Git</code>, <code class="language-plaintext highlighter-rouge">Bash</code> etc.) then this is for you. You can install this new terminal, and configure to suit your taste, and this can <u>host all you command terminals in one place</u>, separated by tabs, their individual settings, themes etc. You can even have background images, including <strong><em>animated GIFs !!</em></strong></p>
<p>Some of the main features:</p>
<ol>
<li>Multiple <strong>tab</strong> support</li>
<li>Accelerated text rendering</li>
<li>Modern text support including <code class="language-plaintext highlighter-rouge">unicode</code>, <code class="language-plaintext highlighter-rouge">emojis</code>, <code class="language-plaintext highlighter-rouge">ligature fonts</code></li>
<li>Configurable <strong>themes</strong>, colors, background image - including <em>animated GIF</em></li>
<li>Fully <strong>configurable terminals</strong> - use any terminal / command-line app</li>
<li>Editable (& sharable) <code class="language-plaintext highlighter-rouge">JSON</code> based settings file</li>
<li>Configurable commands & key shortcuts (through settings)</li>
<li>Configurable copy-paste (I still have trouble using it seamlessly across terminals though)</li>
<li>And many more</li>
<li>Also it’s open source & in full development, so it’ll get better</li>
</ol>
<p><img src="/images/posts/misc/terminal.png" alt="Image" /></p>
<h4 id="settings-hints-to-help-configure-your-own-terminal">Settings hints to help configure your own terminal</h4>
<p class="notice--warning"><strong>Note:</strong> See update later for the latest settings. The profile settings has been updated since <code class="language-plaintext highlighter-rouge">v0.11</code>.</p>
<p>So when you <a href="https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701?activetab=pivot:overviewtab">download</a> and install it from the Microsoft Store, it’s all ready for use. But to use it to it’s potential and you taste, you need to make some adjustments.</p>
<p>I guess in future they’ll provide some UI for the settings, but currently it’s a bare bone <code class="language-plaintext highlighter-rouge">JSON</code> file. To make any changes, you’ll have to update the JSON file manually. For that, click on the drodown button on the top-right corner and select <code class="language-plaintext highlighter-rouge">Settings</code>. It’ll open the <code class="language-plaintext highlighter-rouge">profile.json</code> file that hosts all the settings. It’s just a text file, so you can edit it with any text editor and save it. That’s it! It’ll immediately update the terminal with the changes.</p>
<p class="notice--info"><strong>Note:</strong> You need Windows 10 version 18362.0 or higher for the new Windows Terminal to work. If you don’t have that, update your Windows 10 OS first.</p>
<p>The settings file mainly have four sections</p>
<ol>
<li>The global <strong>app level settings</strong> - how the terminal window behaves, for example how it shows tabs</li>
<li>The <strong>key bindings</strong> - key shortcut for common tasks like open a specific profile on a new tab</li>
<li>The <strong>profiles</strong> - settings for a new tab including command to run, display settings, color settings etc.</li>
<li>The <strong>color schemes</strong> - color settings or themes for profiles are set through <code class="language-plaintext highlighter-rouge">schemes</code>.</li>
</ol>
<p>For the different commands / tools (e.g. <code class="language-plaintext highlighter-rouge">PowerShell</code>, <code class="language-plaintext highlighter-rouge">Bash</code> etc.) you want to run through the terminal, you need to set them up in <strong>profiles</strong>. Each profile can have it’s own command to run. You can also set a bunch of other settings in profile like what should be the starting directory, font face, font size, background color or image, opacity, icon, cursor style etc.</p>
<p>Each profile should have it’s own <code class="language-plaintext highlighter-rouge">Guid</code> that they are identified with. If needed, you can generate your new Guids online. The <code class="language-plaintext highlighter-rouge">defaultProfile</code> at the root level specifies that profile to run on a new tab by default, specified by that profile Guid.</p>
<p>Now for the theme, you can use one of those default color schemes, add your own or can update an existing one. All the color schemes are basically palettes for set of ANSI default colors. To create your own style, just update the color values with #hex codes for your favorite colors. Then add the scheme to a profile using the <code class="language-plaintext highlighter-rouge">name</code> of the scheme.</p>
<p>Following is a part of my own settings which might help you understand it better. See the settings documentation <a href="https://github.com/microsoft/terminal/blob/master/doc/cascadia/SettingsSchema.md">here</a> for more details.</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
<span class="dl">"</span><span class="s2">globals</span><span class="dl">"</span> <span class="p">:</span>
<span class="p">{</span>
<span class="c1">// defaults...</span>
<span class="dl">"</span><span class="s2">keybindings</span><span class="dl">"</span> <span class="p">:</span>
<span class="p">[</span>
<span class="c1">// defaults...</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">command</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">newTabProfile0</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">keys</span><span class="dl">"</span> <span class="p">:</span>
<span class="p">[</span>
<span class="dl">"</span><span class="s2">ctrl+n</span><span class="dl">"</span> <span class="c1">// open new default tab & go to tab</span>
<span class="p">]</span>
<span class="p">},</span>
<span class="c1">// defaults...</span>
<span class="p">],</span>
<span class="dl">"</span><span class="s2">requestedTheme</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">dark</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// theme for title bar etc.</span>
<span class="dl">"</span><span class="s2">showTabsInTitlebar</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">showTerminalTitleInTitlebar</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">false</span>
<span class="p">},</span>
<span class="dl">"</span><span class="s2">profiles</span><span class="dl">"</span> <span class="p">:</span>
<span class="p">[</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">acrylicOpacity</span><span class="dl">"</span> <span class="p">:</span> <span class="mf">0.85</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">backgroundImage</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ms-appdata:///roaming/pubgHD.jpg</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// background image</span>
<span class="dl">"</span><span class="s2">backgroundImageOpacity</span><span class="dl">"</span> <span class="p">:</span> <span class="mf">0.94999998807907104</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">backgroundImageStretchMode</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">uniformToFill</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">closeOnExit</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">colorScheme</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ArghyaMatte</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// custom color scheme</span>
<span class="dl">"</span><span class="s2">commandline</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">powershell.exe</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// program or command to run</span>
<span class="dl">"</span><span class="s2">cursorColor</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#14EA09</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorHeight</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">25</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorShape</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">vintage</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">fontFace</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Fira Code</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// custom font (with ligature)</span>
<span class="dl">"</span><span class="s2">fontSize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">10</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">guid</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">{61c54bbd-c2c6-5271-96e7-009a87ff44bf}</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">historySize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">9001</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">icon</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Windows PowerShell</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">padding</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">10, 5, 10, 0</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// cutom padding</span>
<span class="dl">"</span><span class="s2">snapOnInput</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">startingDirectory</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">C:</span><span class="se">\\</span><span class="s2">Codebase</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// directory to open by default</span>
<span class="dl">"</span><span class="s2">useAcrylic</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">false</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">acrylicOpacity</span><span class="dl">"</span> <span class="p">:</span> <span class="mf">0.7</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">background</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#012456</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// background color</span>
<span class="dl">"</span><span class="s2">closeOnExit</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">colorScheme</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">One Half Dark</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// system color scheme</span>
<span class="dl">"</span><span class="s2">commandline</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">cmd.exe</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorColor</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#14EA09</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// green cursor</span>
<span class="dl">"</span><span class="s2">cursorHeight</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">25</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorShape</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">vintage</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// classic cursor</span>
<span class="dl">"</span><span class="s2">fontFace</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Consolas</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">fontSize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">9</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">guid</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">{0caa0dad-35be-5f56-a8ff-afceeeaa6101}</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">historySize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">9001</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">icon</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ms-appx:///ProfileIcons/{0caa0dad-35be-5f56-a8ff-afceeeaa6101}.png</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Command Prompt</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">padding</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">0, 0, 0, 0</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">snapOnInput</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">startingDirectory</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">%USERPROFILE%</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">useAcrylic</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span>
<span class="p">},</span>
<span class="c1">// Other profiles...</span>
<span class="p">],</span>
<span class="dl">"</span><span class="s2">schemes</span><span class="dl">"</span> <span class="p">:</span>
<span class="p">[</span>
<span class="p">{</span> <span class="c1">// a custom color scheme</span>
<span class="dl">"</span><span class="s2">background</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#262C6B</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// background color</span>
<span class="dl">"</span><span class="s2">black</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#0A2D75</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">blue</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#0965E5</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightBlack</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#555753</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightBlue</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#116CD6</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightCyan</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#34E2E2</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightGreen</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#1AF40E</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightPurple</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#AD7FA8</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightRed</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#DD3E1F</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightWhite</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#DBFDFF</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightYellow</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#F9F90E</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cyan</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#06989A</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">foreground</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#ADCFFF</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// default font color</span>
<span class="dl">"</span><span class="s2">green</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#15A531</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ArghyaMatte</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// the scheme name</span>
<span class="dl">"</span><span class="s2">purple</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#75507B</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">red</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#F90078</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">white</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#21EF4A</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">yellow</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#C4A000</span><span class="dl">"</span>
<span class="p">},</span>
<span class="c1">// defaults...</span>
<span class="p">]</span>
<span class="p">}</span>
</code></pre></div></div>
<p>The preview version is not super stable yet, I’ve faced few crashes myself. But, it’s just an early preview, so I’m sure it’ll get stable in some time and hopefully the team will add lot more handy features in the future.</p>
<h1 id="update-for-settings-v011">Update for settings, v0.11</h1>
<p>The settings got a bunch of updates including some breaking changes in <a href="https://github.com/microsoft/terminal/issues/5458">version 0.11</a>. Now the <code class="language-plaintext highlighter-rouge">profile.json</code> settings file is called <code class="language-plaintext highlighter-rouge">settings.json</code>, usually found in <code class="language-plaintext highlighter-rouge">AppData\Local\Packages\Microsoft.WindowsTerminal_key\LocalState</code>. Check the following links for more details</p>
<ul>
<li><a href="https://devblogs.microsoft.com/commandline/windows-terminal-preview-v0-11-release/">Windows Terminal Preview v0.11 Release</a></li>
<li><a href="https://github.com/microsoft/terminal/issues/3600">Windows Terminal Status Updates</a></li>
</ul>
<p>If you want to apply the same settings as above, your new <code class="language-plaintext highlighter-rouge">settings.json</code> will look like</p>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// This file was initially generated by Windows Terminal 1.0.1811.0</span>
<span class="c1">// To view the default settings, hold "alt" while clicking on the "Settings" button.</span>
<span class="c1">// For documentation on these settings, see: https://aka.ms/terminal-documentation</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">$schema</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">https://aka.ms/terminal-profiles-schema</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">defaultProfile</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">{61c54bbd-c2c6-5271-96e7-009a87ff44bf}</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">copyOnSelect</span><span class="dl">"</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">copyFormatting</span><span class="dl">"</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="c1">// Apply custom settings</span>
<span class="c1">// To learn more about profiles, visit https://aka.ms/terminal-profile-settings</span>
<span class="dl">"</span><span class="s2">theme</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">dark</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// CHANGED from requestedTheme</span>
<span class="dl">"</span><span class="s2">showTabsInTitlebar</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">showTerminalTitleInTitlebar</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">wordDelimiters</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2"> ./</span><span class="se">\\</span><span class="s2">()</span><span class="se">\"</span><span class="s2">'-:,.;<>~!@#$%^&*|+=[]{}~?</span><span class="se">\</span><span class="s2">u2502</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">alwaysShowTabs</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">initialCols</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">120</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">initialRows</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">30</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">profiles</span><span class="dl">"</span><span class="p">:</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">defaults</span><span class="dl">"</span><span class="p">:</span>
<span class="p">{</span>
<span class="c1">// Put settings here that you want to apply to all profiles.</span>
<span class="p">},</span>
<span class="dl">"</span><span class="s2">list</span><span class="dl">"</span><span class="p">:</span>
<span class="p">[</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">acrylicOpacity</span><span class="dl">"</span> <span class="p">:</span> <span class="mf">0.85</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">backgroundImage</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ms-appdata:///roaming/pubgHD.jpg</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// background image</span>
<span class="dl">"</span><span class="s2">backgroundImageOpacity</span><span class="dl">"</span> <span class="p">:</span> <span class="mf">0.94999998807907104</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">backgroundImageStretchMode</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">uniformToFill</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">closeOnExit</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">colorScheme</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ArghyaMatte</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// custom color scheme</span>
<span class="dl">"</span><span class="s2">commandline</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">powershell.exe</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// program or command to run</span>
<span class="dl">"</span><span class="s2">cursorColor</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#14EA09</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorHeight</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">25</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorShape</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">vintage</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">fontFace</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Fira Code</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// custom font (with ligature)</span>
<span class="dl">"</span><span class="s2">fontSize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">10</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">guid</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">{61c54bbd-c2c6-5271-96e7-009a87ff44bf}</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">historySize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">9001</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">icon</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Windows PowerShell</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">padding</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">10, 5, 10, 0</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// cutom padding</span>
<span class="dl">"</span><span class="s2">snapOnInput</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">startingDirectory</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">C:</span><span class="se">\\</span><span class="s2">Codebase</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// directory to open by default</span>
<span class="dl">"</span><span class="s2">useAcrylic</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">false</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">acrylicOpacity</span><span class="dl">"</span> <span class="p">:</span> <span class="mf">0.7</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">background</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#012456</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// background color</span>
<span class="dl">"</span><span class="s2">closeOnExit</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">colorScheme</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">One Half Dark</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// system color scheme</span>
<span class="dl">"</span><span class="s2">commandline</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">cmd.exe</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorColor</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#14EA09</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// green cursor</span>
<span class="dl">"</span><span class="s2">cursorHeight</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">25</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cursorShape</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">vintage</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// classic cursor</span>
<span class="dl">"</span><span class="s2">fontFace</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Consolas</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">fontSize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">9</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">guid</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">{0caa0dad-35be-5f56-a8ff-afceeeaa6101}</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">historySize</span><span class="dl">"</span> <span class="p">:</span> <span class="mi">9001</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">icon</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ms-appx:///ProfileIcons/{0caa0dad-35be-5f56-a8ff-afceeeaa6101}.png</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">Command Prompt</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">padding</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">0, 0, 0, 0</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">snapOnInput</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">startingDirectory</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">%USERPROFILE%</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">useAcrylic</span><span class="dl">"</span> <span class="p">:</span> <span class="kc">true</span>
<span class="p">},</span>
<span class="c1">// Other profiles...</span>
<span class="p">]</span>
<span class="p">},</span>
<span class="c1">// Add custom color schemes to this array.</span>
<span class="c1">// To learn more about color schemes, visit https://aka.ms/terminal-color-schemes</span>
<span class="dl">"</span><span class="s2">schemes</span><span class="dl">"</span><span class="p">:</span>
<span class="p">[</span>
<span class="p">{</span> <span class="c1">// a custom color scheme</span>
<span class="dl">"</span><span class="s2">background</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#262C6B</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// background color</span>
<span class="dl">"</span><span class="s2">black</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#0A2D75</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">blue</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#0965E5</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightBlack</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#555753</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightBlue</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#116CD6</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightCyan</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#34E2E2</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightGreen</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#1AF40E</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightPurple</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#AD7FA8</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightRed</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#DD3E1F</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightWhite</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#DBFDFF</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">brightYellow</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#F9F90E</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">cyan</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#06989A</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">foreground</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#ADCFFF</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// default font color</span>
<span class="dl">"</span><span class="s2">green</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#15A531</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">name</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">ArghyaMatte</span><span class="dl">"</span><span class="p">,</span> <span class="c1">// the scheme name</span>
<span class="dl">"</span><span class="s2">purple</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#75507B</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">red</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#F90078</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">white</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#21EF4A</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">yellow</span><span class="dl">"</span> <span class="p">:</span> <span class="dl">"</span><span class="s2">#C4A000</span><span class="dl">"</span>
<span class="p">},</span>
<span class="c1">// other schemes...</span>
<span class="p">],</span>
<span class="c1">// Add custom keybindings to this array.</span>
<span class="c1">// To learn more about keybindings, visit https://aka.ms/terminal-keybindings</span>
<span class="dl">"</span><span class="s2">keybindings</span><span class="dl">"</span><span class="p">:</span>
<span class="p">[</span>
<span class="p">{</span> <span class="dl">"</span><span class="s2">command</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span><span class="dl">"</span><span class="s2">action</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">copy</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">singleLine</span><span class="dl">"</span><span class="p">:</span> <span class="kc">false</span> <span class="p">},</span> <span class="dl">"</span><span class="s2">keys</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">ctrl+c</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="dl">"</span><span class="s2">command</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">paste</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">keys</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">ctrl+v</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="dl">"</span><span class="s2">command</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">find</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">keys</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">ctrl+shift+f</span><span class="dl">"</span> <span class="p">},</span>
<span class="p">{</span> <span class="dl">"</span><span class="s2">command</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span> <span class="dl">"</span><span class="s2">action</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">splitPane</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">split</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">auto</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">splitMode</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">duplicate</span><span class="dl">"</span> <span class="p">},</span> <span class="dl">"</span><span class="s2">keys</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">alt+shift+d</span><span class="dl">"</span> <span class="p">},</span>
<span class="c1">// Open a new tab with default profile</span>
<span class="p">{</span> <span class="dl">"</span><span class="s2">command</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span> <span class="dl">"</span><span class="s2">action</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">newTab</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">index</span><span class="dl">"</span><span class="p">:</span> <span class="mi">0</span> <span class="p">},</span> <span class="dl">"</span><span class="s2">keys</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">ctrl+n</span><span class="dl">"</span> <span class="p">}</span>
<span class="c1">// See default key bindings at https://github.com/microsoft/terminal/issues/3600</span>
<span class="p">]</span>
<span class="p">}</span>
</code></pre></div></div>
<h3 id="some-useful-links">Some useful links</h3>
<ul>
<li><a href="https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701?activetab=pivot:overviewtab">Download</a></li>
<li><a href="https://github.com/microsoft/terminal">Source code</a></li>
<li><a href="https://github.com/microsoft/terminal/blob/master/doc/cascadia/SettingsSchema.md">Settings docs</a></li>
<li><a href="https://www.hanselman.com/blog/YouCanNowDownloadTheNewOpenSourceWindowsTerminal.aspx">Scott Hanselman’s tips</a></li>
<li><a href="https://github.com/felixse/FluentTerminal">Fluent terminal</a></li>
<li><a href="https://docs.microsoft.com/en-us/windows/terminal/tutorials/powerline-setup">Powerline setup, GIT terminal - docs</a></li>
<li><a href="https://www.hanselman.com/blog/HowToMakeAPrettyPromptInWindowsTerminalWithPowerlineNerdFontsCascadiaCodeWSLAndOhmyposh.aspx">More customization - Hanselman</a></li>
</ul>The new Terminal for Windows 10 is now available for download (preview) in the Microsoft store. It's sooo coolC# 7.2 safe & efficient enhancement of value types2018-12-11T00:00:00+00:002018-12-11T00:00:00+00:00https://arghya.xyz/articles/c-sharp-7.2-value-type-enhancements<h1 id="value-type-enhancements-in-c-72">Value type enhancements in C# 7.2</h1>
<p><strong><em>This is mostly a bunch of code demos, not so much into the theories.</em></strong></p>
<p>This is part of series where we discuss C# language enhancements in version <code class="language-plaintext highlighter-rouge">C# 6</code> and above. In this article we’ll discuss a group of features introduced in <code class="language-plaintext highlighter-rouge">C# 7.2</code>, for safe and efficient coding with value types. <strong>If you are not familiar with the previous versions yet, go and read the <a href="/articles/new-features-of-csharp-6">C# 6</a>, <a href="/articles/new-features-of-csharp-7">C# 7</a> and <a href="/articles/c-sharp-7-minor-versions">C# 7.1 - 7.3</a> articles first.</strong></p>
<p><strong><code class="language-plaintext highlighter-rouge">C# 7.2</code></strong> brings in a set of new features that makes working with value types (<code class="language-plaintext highlighter-rouge">struct</code> in <code class="language-plaintext highlighter-rouge">C#</code>) more efficient and semantically better. Most of them make efficient use of memory for better performance, also provides immutability to avoid unintentional changes in data wherever possible. This features make writing high performance code easier & cleaner and safer to write low level code with better control on memory allocation.</p>
<blockquote>
<p>C# 7.2 is another point release that adds a number of useful features. One theme for this release is working more efficiently with value types by avoiding unnecessary copies or allocations. - <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2">docs</a></p>
</blockquote>
<h2 id="struct-in-net">Struct in .NET</h2>
<p>What is a <code class="language-plaintext highlighter-rouge">struct</code> in .NET?</p>
<p>Similar to <code class="language-plaintext highlighter-rouge">class</code>, a <code class="language-plaintext highlighter-rouge">struct</code> is a compound data type that can pack together multiple data pieces (properties, fields) and behaviours (methods, events, indexers). A <code class="language-plaintext highlighter-rouge">struct</code> is a <code class="language-plaintext highlighter-rouge">value type</code>, means it is passed around as a complete value and assigning it to a new variable makes a complete new copy of the data. On the other hand, classes are reference type, and are passed around as references. Copying a class instance just creates a new reference to the same memory address.</p>
<p>Generally struct objects are stored as a single chunk of memory in the stack (not always though, e.g. when they are used as property of a class object).</p>
<p>Class & struct can both have methods, properties, indexers & events. They both can implement interface (though casting a struct to interface type boxes it to a reference). But, there are some differences</p>
<ol>
<li>Classes can inherit from another class, struct cannot inherit from anything</li>
<li>Struct cannot have explicit (defined in code) parameter-less constructor</li>
<li>Struct cannot have a destructor</li>
<li>Struct has default implementation of <code class="language-plaintext highlighter-rouge">Equals()</code> that matches by value equality of data/properties</li>
</ol>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">interface</span> <span class="nc">IAnimal</span>
<span class="p">{</span>
<span class="kt">string</span> <span class="nf">MakeNoise</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">DogFamily</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">virtual</span> <span class="kt">string</span> <span class="nf">MakeNoise</span><span class="p">()</span> <span class="p">=></span> <span class="s">"Aaooo"</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1">//class can implement interface & inherit class but NOT struct</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">Husky</span> <span class="p">:</span> <span class="n">DogFamily</span><span class="p">,</span> <span class="n">IAnimal</span> <span class="c1">//Polygon</span>
<span class="p">{</span>
<span class="k">public</span> <span class="nf">Husky</span><span class="p">()</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">//constructor</span>
<span class="p">~</span><span class="nf">Husky</span><span class="p">()</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">//destructor </span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">struct</span> <span class="nc">Polygon</span>
<span class="p">{</span>
<span class="c1">//struct CANNOT have explicit parameterless constructor</span>
<span class="k">public</span> <span class="nf">Polygon</span><span class="p">(</span><span class="kt">int</span> <span class="n">sides</span><span class="p">)</span> <span class="c1">//a simple constructor</span>
<span class="p">{</span>
<span class="n">Sides</span> <span class="p">=</span> <span class="n">sides</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1">//can have properties, methods, events & indexers</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">Sides</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="c1">//ONLY classes can have destructors, NOT structs</span>
<span class="c1">//~Polygon() { }</span>
<span class="p">}</span>
<span class="c1">//struct can only implement interface, CANNOT inherit class or struct</span>
<span class="k">public</span> <span class="k">struct</span> <span class="nc">Rectangle</span> <span class="p">:</span> <span class="n">IAnimal</span> <span class="c1">//Polygon</span>
<span class="p">{</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">Height</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">Width</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="c1">//this is bad example, do not do in real code (impractical & breaks LSP)</span>
<span class="k">public</span> <span class="kt">string</span> <span class="nf">MakeNoise</span><span class="p">()</span> <span class="p">=></span> <span class="k">throw</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="nf">NotImplementedException</span><span class="p">();</span>
<span class="c1">//Struct DOES supports Deconstructor like class (C# 7.0)</span>
<span class="c1">//needs System.ValueTuple NuGet for < .NET 4.6.2, .NET Core 1.x, .NET Standard 1.x</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">Deconstruct</span><span class="p">(</span><span class="k">out</span> <span class="kt">int</span> <span class="n">height</span><span class="p">,</span> <span class="k">out</span> <span class="kt">int</span> <span class="n">width</span><span class="p">)</span>
<span class="p">=></span> <span class="p">(</span><span class="n">height</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span> <span class="p">=</span> <span class="p">(</span><span class="n">Height</span><span class="p">,</span> <span class="n">Width</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="so-when-should-you-use-struct">So, when should you use struct?</h4>
<p>In .NET, generally classes are preferred. If you are not sure, go with a class.</p>
<p>But struct can have some benefits (e.g. performance & memory overhead) in some scenarios. Allocating and deallocating small piece of memory (allocating memory on heap, generating reference on stack etc.) and the process of garbage collection may be heavier for classes than using structs, which just keeps the whole thing on stack. Another scenario, e.g. creating a 10 item array with reference type creates 11 references, for the 10 items and one for the array. When the same is created for struct, only a single reference is created for the array which holds the whole chunk of data with 10 structs. But having heavy structs can choke the stack memory, and passing them around as parameters can be expensive as that copies the whole data every time.</p>
<p>Structs are specifically useful when there are <u>large number of short lived, small piece of data</u> and data that follows <strong>value type semantics</strong>, i.e. data that semantically represents a single value (e.g. a decimal number or a coordinate point), rather than a complex object (e.g. a person with height, weight, age, name, gender, job, address etc.). Another important point is, value type should equate when their values are same (default behaviour of <code class="language-plaintext highlighter-rouge">Equals()</code> in structs) and need not have same reference. (The <code class="language-plaintext highlighter-rouge">string</code> is an exception where it is a reference type but equality matches by value!)</p>
<p>An array of struct takes up one contiguous memory block with a single reference, making it more performant (not while passing around though). Also, a large size struct array <em>will generally</em> grow on <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap">LOH memory</a> and bypass the GC compaction, thus further improving the performance. So, this also makes a good case for structs. There are some <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct">standard rules</a> for when to consider struct over class:</p>
<ol>
<li>It logically represents a single value, similar to primitive types (e.g. a decimal number or a coordinate point) - i.e. it follows value semantics. This is probably the single most important factor deciding when to use struct</li>
<li>It has an instance size smaller than 16 bytes (small, packing a few value type data)</li>
<li>It is immutable (well, always depends on actual implementation)</li>
<li>It will not have to be boxed frequently (not casted frequently, e.g. to an interface)</li>
</ol>
<p class="notice--info"><strong>Note:</strong> Value types can be passed <strong>by-value</strong> or <strong>by-reference</strong> to a method. <strong>[1]</strong> When passing by-value, a copy of data is made and passed to the parameter. <strong>[2]</strong> When passed by reference, no copy is made and a reference to the original data is passed, so any change inside the called method reflects in the original data.</p>
<p>So we have 2 options to pass a value type, let’s look at the <strong>drawbacks</strong> of both</p>
<ol>
<li>By-value: The actual data is copied, so it can be expensive for large data</li>
<li>By-reference: Not copied, but now the data is open for modification even if unintentional (remember, struct should be immutable)</li>
</ol>
<p>The following bunch of new features released with <code class="language-plaintext highlighter-rouge">C# 7.2</code> (and a bit with <code class="language-plaintext highlighter-rouge">C# 7.3</code>), has the same common theme - increasing efficiency of value types, by enabling them to be passed like reference, while keeping them immutable whenever possible. With these new capabilities of <code class="language-plaintext highlighter-rouge">C#</code>, we can have significant performance improvement in some scenarios specially with large value type data. Also they improve the readability of the language by making programming intent clearer. But, please note that all these should be used <strong>only in high performance scenarios</strong>. Using them for a standard applications that already uses lot of memory and resources, might be just an unnecessary micro-optimization.</p>
<h4 id="in-modifier-on-parameter"><code class="language-plaintext highlighter-rouge">In</code> modifier on parameter</h4>
<p>We already have <code class="language-plaintext highlighter-rouge">ref</code> and <code class="language-plaintext highlighter-rouge">out</code> modifiers on parameters, <code class="language-plaintext highlighter-rouge">C# 7.2</code> introduces <code class="language-plaintext highlighter-rouge">in</code>.</p>
<p>It means that a parameter is passed by reference but cannot be modified by the calling method. Internally it works similar to <code class="language-plaintext highlighter-rouge">ref</code> parameters, but compiler does additional checks to see it was not modified in the method (beyond compiler, <code class="language-plaintext highlighter-rouge">out</code> and <code class="language-plaintext highlighter-rouge">in</code> are both <code class="language-plaintext highlighter-rouge">ref</code> with some additional restrictions). This is more useful for readability of code specifying the intent is to use as <code class="language-plaintext highlighter-rouge">in</code>put parameter only, not to be modified. It also improves performance by the compiler not having to copy the value. Note that the variable <strong>must be initialized</strong> before calling the method, with that variable as parameter. Semantically, it, kind of, works as opposite of <code class="language-plaintext highlighter-rouge">out</code>.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//Standard use of ref and out parameters</span>
<span class="c1">//out parameter need not be initialized</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">Half</span><span class="p">(</span><span class="k">ref</span> <span class="kt">double</span> <span class="k">value</span><span class="p">,</span> <span class="k">out</span> <span class="kt">double</span> <span class="n">result</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">input</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span> <span class="c1">//read from ref parameter</span>
<span class="k">value</span> <span class="p">=</span> <span class="n">input</span> <span class="p">/</span> <span class="m">2</span><span class="p">;</span> <span class="c1">//setting value to ref, not super intuitive but fine</span>
<span class="n">result</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span> <span class="c1">//setting value of out parameter, pretty clean</span>
<span class="p">}</span>
<span class="c1">//Using in modifier to better represent intent</span>
<span class="k">public</span> <span class="kt">double</span> <span class="nf">Square</span><span class="p">(</span><span class="k">in</span> <span class="kt">double</span> <span class="k">value</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">//following line does not compile, as it tries to set value of in-parameter</span>
<span class="c1">//value = value * value; //>>>> error: in double variable is readonly <<<<</span>
<span class="k">return</span> <span class="k">value</span> <span class="p">*</span> <span class="k">value</span><span class="p">;</span> <span class="c1">//reading an in parameter is fine</span>
<span class="p">}</span>
</code></pre></div></div>
<p class="notice--info"><strong>Notes:</strong> <strong>[1]</strong>An argument that is passed to a <code class="language-plaintext highlighter-rouge">ref</code> or <code class="language-plaintext highlighter-rouge">in</code> parameter must be initialized before it is passed. This differs from <code class="language-plaintext highlighter-rouge">out</code> parameters, whose arguments do not have to be explicitly initialized before they are passed. They can also be defined inline. <strong>[2]</strong> Members of a class can’t have signatures that differ only by <code class="language-plaintext highlighter-rouge">ref</code>, <code class="language-plaintext highlighter-rouge">in</code>, or <code class="language-plaintext highlighter-rouge">out</code>. BUT, methods can be overloaded by using <code class="language-plaintext highlighter-rouge">ref</code>, <code class="language-plaintext highlighter-rouge">in</code>, or <code class="language-plaintext highlighter-rouge">out</code> when the other one has a simple value type parameter. (Remember: to the compiler, they all are <code class="language-plaintext highlighter-rouge">ref</code>) <strong>[3]</strong> <code class="language-plaintext highlighter-rouge">async</code> methods can NOT have <code class="language-plaintext highlighter-rouge">ref</code>, <code class="language-plaintext highlighter-rouge">in</code>, or <code class="language-plaintext highlighter-rouge">out</code> parameters. Same with iterator methods with <code class="language-plaintext highlighter-rouge">yield</code>. <strong>[4]</strong> When reference types are passed by-reference as parameter, the called method can completely replace the object by pointing the reference to a new location (assigning a <code class="language-plaintext highlighter-rouge">new</code> object). So now, the original variable in calling method will have a new object. This is not possible when reference type is passed by-value, only individual items can be updated in-place. If a new object is assigned to pass-by-value reference parameter inside called method, further changes to that object does not reflect in original object passed!</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ExampleClass</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">M</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
<span class="c1">//This works (any ONE of following three is allowed)</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">M</span><span class="p">(</span><span class="k">ref</span> <span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
<span class="c1">//But the following 2 does NOT compile, if above is present</span>
<span class="c1">//public void M(in int x) { }</span>
<span class="c1">//public void M(out int x) => x = 10;</span>
<span class="c1">//following methods do not work if parameter has ref or other modifiers</span>
<span class="k">public</span> <span class="n">IEnumerable</span><span class="p"><</span><span class="kt">int</span><span class="p">></span> <span class="nf">GetNumbers</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">1</span><span class="p">;</span> <span class="n">i</span> <span class="p"><=</span> <span class="n">x</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
<span class="k">yield</span> <span class="k">return</span> <span class="n">i</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span><span class="p"><</span><span class="kt">int</span><span class="p">></span> <span class="nf">GetDoubleAsync</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">await</span> <span class="n">Task</span><span class="p">.</span><span class="nf">Delay</span><span class="p">(</span><span class="m">100</span><span class="p">);</span>
<span class="k">return</span> <span class="n">x</span> <span class="p">*</span> <span class="m">2</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p class="notice--info"><strong>Note:</strong> When calling a method with <code class="language-plaintext highlighter-rouge">in</code> parameter, the <code class="language-plaintext highlighter-rouge">in</code> keyword is optional. But, if 2 methods differ by only a <code class="language-plaintext highlighter-rouge">in</code> modifier in a parameter, then the <code class="language-plaintext highlighter-rouge">in</code> keyword must be used to call the method that has in parameter. (This was fixed in <code class="language-plaintext highlighter-rouge">C# 7.3</code>).</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">M1</span><span class="p">(</span><span class="k">in</span> <span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">M2</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">M2</span><span class="p">(</span><span class="k">in</span> <span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">//in overload</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">TestIn</span><span class="p">()</span>
<span class="p">{</span>
<span class="nf">M1</span><span class="p">(</span><span class="m">10</span><span class="p">);</span> <span class="c1">//works fine</span>
<span class="c1">//following is NOT allowed - only pass variable with `in`</span>
<span class="c1">//M1(in 30);</span>
<span class="kt">var</span> <span class="n">n</span> <span class="p">=</span> <span class="m">30</span><span class="p">;</span>
<span class="nf">M1</span><span class="p">(</span><span class="k">in</span> <span class="n">n</span><span class="p">);</span> <span class="c1">//this works</span>
<span class="nf">M2</span><span class="p">(</span><span class="n">n</span><span class="p">);</span> <span class="c1">//calls first M2</span>
<span class="nf">M2</span><span class="p">(</span><span class="k">in</span> <span class="n">n</span><span class="p">);</span> <span class="c1">//calls second M2</span>
<span class="p">}</span>
<span class="c1">//in parameters CAN have default values</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">M3</span><span class="p">(</span><span class="k">in</span> <span class="kt">int</span> <span class="n">x</span> <span class="p">=</span> <span class="m">100</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">//valid</span>
</code></pre></div></div>
<p>For value types, <code class="language-plaintext highlighter-rouge">readonly struct</code> (see below) and <code class="language-plaintext highlighter-rouge">in</code> parameters play very well together. In fact, passing a non-readonly struct as <code class="language-plaintext highlighter-rouge">in</code> parameter <a href="https://blogs.msdn.microsoft.com/seteplia/2018/03/07/the-in-modifier-and-the-readonly-structs-in-c/">almost always degrades the performance</a>.</p>
<h4 id="readonly-struct"><code class="language-plaintext highlighter-rouge">readonly struct</code></h4>
<p>When a struct is defined with <code class="language-plaintext highlighter-rouge">readonly</code> modifier, the structure becomes immutable. Simply put, all it’s member fields & properties must be readonly. The <code class="language-plaintext highlighter-rouge">this</code> fields can be set only within a constructor. So, once initialized, the values cannot be updated (well, not without tricks like <code class="language-plaintext highlighter-rouge">reflection</code>). This was kind of a long due feature, developers wanted a clear way to create immutable value types, which was not there. This is useful for it’s clear readability of intent, but also very useful from the performance stand point as it saves the compiler from making a defensive copy of the data when passing around. Read <a href="https://blogs.msdn.microsoft.com/seteplia/2018/03/07/the-in-modifier-and-the-readonly-structs-in-c/">this</a> for better understanding.</p>
<p>Readonly structs should always be passed as <code class="language-plaintext highlighter-rouge">in</code> parameters to have better performance (by avoiding a defensive copy by the compiler).</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">readonly</span> <span class="k">struct</span> <span class="nc">Velocity</span>
<span class="p">{</span>
<span class="c1">//All fields & properties MUST BE READONLY</span>
<span class="k">private</span> <span class="k">readonly</span> <span class="kt">string</span> <span class="n">_direction</span><span class="p">;</span>
<span class="k">public</span> <span class="kt">double</span> <span class="n">Speed</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="p">}</span>
<span class="k">public</span> <span class="kt">string</span> <span class="n">Unit</span> <span class="p">=></span> <span class="s">"m/s"</span><span class="p">;</span>
<span class="c1">//readonly fileds/properties can only be set in constructor </span>
<span class="k">public</span> <span class="nf">Velocity</span><span class="p">(</span><span class="kt">double</span> <span class="n">speed</span><span class="p">,</span> <span class="kt">string</span> <span class="n">direction</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">Speed</span> <span class="p">=</span> <span class="n">speed</span><span class="p">;</span>
<span class="n">_direction</span> <span class="p">=</span> <span class="n">direction</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1">//this is allowed too, only inside constructor </span>
<span class="k">public</span> <span class="nf">Velocity</span><span class="p">(</span><span class="n">Velocity</span> <span class="n">v</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">this</span> <span class="p">=</span> <span class="n">v</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c1">//ideal usage with in parameters</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">TestReadonlyStruct</span><span class="p">(</span><span class="k">in</span> <span class="n">Velocity</span> <span class="n">velocity</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">speed</span> <span class="p">=</span> <span class="n">velocity</span><span class="p">.</span><span class="n">Speed</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note that there is generally no point creating an instance of <code class="language-plaintext highlighter-rouge">readonly struct</code> by calling the default constructor, as that will give you an instance with all properties/fields set to default values and you cannot change it!</p>
<h4 id="ref-struct"><code class="language-plaintext highlighter-rouge">ref struct</code></h4>
<p>Adding the <code class="language-plaintext highlighter-rouge">ref</code> modifier to a struct declaration defines that instances of that type <strong>must be stack allocated</strong>. In other words, instances of these types can never be created on the heap as a member of another class, or they cannot be boxed, they cannot be assigned to variables of type <code class="language-plaintext highlighter-rouge">object</code>, <code class="language-plaintext highlighter-rouge">dynamic</code> or to any <code class="language-plaintext highlighter-rouge">interface</code> type. Obviously, they cannot implement an interface. There are bunch of <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref#ref-struct-types">rules</a> that the compiler enforces on a <code class="language-plaintext highlighter-rouge">ref struct</code>.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//a ref struct looks like just a struct</span>
<span class="k">public</span> <span class="k">ref</span> <span class="k">struct</span> <span class="nc">Temperature</span>
<span class="p">{</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">Value</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">Unit</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
<span class="c1">//usage</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">TestRefStruct</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">//velocity is a normal (readonly) struct defined above</span>
<span class="kt">var</span> <span class="n">readonlyStruct</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Velocity</span><span class="p">(</span><span class="m">10</span><span class="p">,</span> <span class="s">"NW"</span><span class="p">);</span>
<span class="kt">object</span> <span class="n">boxed</span> <span class="p">=</span> <span class="n">readonlyStruct</span><span class="p">;</span> <span class="c1">//struct can be boxed</span>
<span class="kt">var</span> <span class="n">refStruct</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Temperature</span><span class="p">();</span> <span class="c1">//a ref struct <<<<</span>
<span class="c1">//ref struct CANNOT be boxed</span>
<span class="c1">//boxed = refStruct; //NOT ALLOWED</span>
<span class="c1">//this also NOT ALLOWED, see below</span>
<span class="c1">//var refStructString = refStruct.ToString();</span>
<span class="p">}</span>
<span class="k">class</span> <span class="nc">Class1</span> <span class="c1">//a normal class</span>
<span class="p">{</span>
<span class="k">public</span> <span class="n">Velocity</span> <span class="n">Velocity</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span> <span class="c1">//struct property</span>
<span class="c1">//NOT ALLOWED - ref struct CANNOT be property of a class</span>
<span class="c1">//public Temperature Temperature { get; set; }</span>
<span class="p">}</span>
<span class="k">ref</span> <span class="k">struct</span> <span class="nc">Weather</span> <span class="c1">//another ref struct</span>
<span class="p">{</span>
<span class="c1">//works: ref struct CAN be used as property</span>
<span class="c1">//of another ref struct ONLY</span>
<span class="k">public</span> <span class="n">Temperature</span> <span class="n">Temperature</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p class="notice--info"><strong>Note</strong>: A <code class="language-plaintext highlighter-rouge">ref struct</code> is also called an <strong><code class="language-plaintext highlighter-rouge">embedded reference</code></strong>. Because of the object casting not being allowed, you cannot call methods like <code class="language-plaintext highlighter-rouge">ToSTring()</code>, <code class="language-plaintext highlighter-rouge">Equals()</code>, <code class="language-plaintext highlighter-rouge">GetHashCode()</code> on an instance of a <code class="language-plaintext highlighter-rouge">ref struct</code>. The only use of <code class="language-plaintext highlighter-rouge">ref struct</code> variables are in method parameters or local variables. You can also have <code class="language-plaintext highlighter-rouge">readonly ref struct</code> which follows the rules from both the types.</p>
<h4 id="ref-readonly-modifier-on-parameter"><code class="language-plaintext highlighter-rouge">ref readonly</code> modifier on parameter</h4>
<p>Can be beneficial when returning large structures, as it saves copying the value while maintaining immutability of returned data. So, when you do a <code class="language-plaintext highlighter-rouge">ref readonly</code> on a method, it returns a reference to the returned (<code class="language-plaintext highlighter-rouge">ref return</code>) item, but the calling method is not allowed to make any changes to it. It can only read the data from the returned reference.</p>
<p>The <code class="language-plaintext highlighter-rouge">ref readonly</code> kind of puts the same restrictions as <code class="language-plaintext highlighter-rouge">in</code> but on the returning side.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">struct</span> <span class="nc">Coordinate</span>
<span class="p">{</span>
<span class="k">public</span> <span class="nf">Coordinate</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">,</span> <span class="kt">int</span> <span class="n">y</span><span class="p">)</span> <span class="c1">//simple constructor</span>
<span class="p">{</span>
<span class="n">X</span> <span class="p">=</span> <span class="n">x</span><span class="p">;</span>
<span class="n">Y</span> <span class="p">=</span> <span class="n">y</span><span class="p">;</span>
<span class="n">_array</span> <span class="p">=</span> <span class="k">null</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">private</span> <span class="n">Coordinate</span><span class="p">[]</span> <span class="n">_array</span><span class="p">;</span> <span class="c1">//fileds & properties</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">X</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="k">public</span> <span class="kt">int</span> <span class="n">Y</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="c1">//just a simple method to set internal array</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">SetCoordinates</span><span class="p">(</span><span class="n">Coordinate</span><span class="p">[]</span> <span class="n">coordinates</span><span class="p">)</span> <span class="p">=></span> <span class="n">_array</span> <span class="p">=</span> <span class="n">coordinates</span><span class="p">;</span>
<span class="c1">// >>>> REF READONLY <<<<</span>
<span class="k">public</span> <span class="k">ref</span> <span class="k">readonly</span> <span class="n">Coordinate</span> <span class="nf">GetCoordinate</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">_array</span> <span class="p">==</span> <span class="k">null</span> <span class="p">||</span> <span class="n">x</span> <span class="p"><</span> <span class="m">0</span> <span class="p">||</span> <span class="n">x</span> <span class="p">>=</span> <span class="n">_array</span><span class="p">.</span><span class="n">Length</span><span class="p">)</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentException</span><span class="p">();</span>
<span class="k">return</span> <span class="k">ref</span> <span class="n">_array</span><span class="p">[</span><span class="n">x</span><span class="p">];</span> <span class="c1">//notice signature & return statement</span>
<span class="p">}</span>
<span class="k">public</span> <span class="kt">string</span> <span class="nf">GetItemsAsString</span><span class="p">()</span> <span class="c1">//just a utility to print the array</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">_array</span> <span class="p">==</span> <span class="k">null</span> <span class="p">?</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span>
<span class="p">:</span> <span class="kt">string</span><span class="p">.</span><span class="nf">Join</span><span class="p">(</span><span class="s">" - "</span><span class="p">,</span> <span class="n">_array</span><span class="p">.</span><span class="nf">Select</span><span class="p">(</span><span class="n">a</span> <span class="p">=></span> <span class="s">$"</span><span class="p">{</span><span class="n">a</span><span class="p">.</span><span class="n">X</span><span class="p">}</span><span class="s">,</span><span class="p">{</span><span class="n">a</span><span class="p">.</span><span class="n">Y</span><span class="p">}</span><span class="s">"</span><span class="p">));</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">TestRefReadonly</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">structArr</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Coordinate</span><span class="p">[]</span> <span class="p">{</span> <span class="k">new</span> <span class="nf">Coordinate</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">),</span> <span class="k">new</span> <span class="nf">Coordinate</span><span class="p">(</span><span class="m">2</span><span class="p">,</span> <span class="m">4</span><span class="p">),</span> <span class="k">new</span> <span class="nf">Coordinate</span><span class="p">(</span><span class="m">3</span><span class="p">,</span> <span class="m">6</span><span class="p">)</span> <span class="p">};</span>
<span class="kt">var</span> <span class="n">coordinate</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Coordinate</span><span class="p">();</span>
<span class="n">coordinate</span><span class="p">.</span><span class="nf">SetCoordinates</span><span class="p">(</span><span class="n">structArr</span><span class="p">);</span>
<span class="c1">//without `ref` it just passes by value (a copy)</span>
<span class="kt">var</span> <span class="n">coByVal</span> <span class="p">=</span> <span class="n">coordinate</span><span class="p">.</span><span class="nf">GetCoordinate</span><span class="p">(</span><span class="m">1</span><span class="p">);</span>
<span class="n">coByVal</span><span class="p">.</span><span class="n">Y</span> <span class="p">=</span> <span class="m">100</span><span class="p">;</span> <span class="c1">//coByVal = 2,100</span>
<span class="kt">var</span> <span class="n">originalData</span> <span class="p">=</span> <span class="n">coordinate</span><span class="p">.</span><span class="nf">GetItemsAsString</span><span class="p">();</span> <span class="c1">//1,2 - 2,4 - 3,6</span>
<span class="c1">// >>>> REF READONLY actual usage SYNTAX <<<<</span>
<span class="c1">//Actual use of ref readonly for readonly (immutable) reference</span>
<span class="k">ref</span> <span class="k">readonly</span> <span class="kt">var</span> <span class="n">coByRef</span> <span class="p">=</span> <span class="k">ref</span> <span class="n">coordinate</span><span class="p">.</span><span class="nf">GetCoordinate</span><span class="p">(</span><span class="m">1</span><span class="p">);</span>
<span class="c1">//coByRef.Y = 100; >>>> this is NOT allowed <<<<</span>
<span class="kt">var</span> <span class="n">y</span> <span class="p">=</span> <span class="n">coByRef</span><span class="p">.</span><span class="n">Y</span><span class="p">;</span> <span class="c1">//coByRef = 2,4 - gets the value fine, as ref</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="spant-and-memoryt"><code class="language-plaintext highlighter-rouge">Span<T></code> and <code class="language-plaintext highlighter-rouge">Memory<T></code></h4>
<p>Though not part of <code class="language-plaintext highlighter-rouge">C# 7.2</code> or any other language specification, these 2 types were added as core framework enhancement with new constructs like <code class="language-plaintext highlighter-rouge">ref struct</code> being available. The <code class="language-plaintext highlighter-rouge">Span<T></code> is a ref struct that given a high performance, universal access to contiguous memory space across stack, managed heap or unmanaged heap. The <code class="language-plaintext highlighter-rouge">Memory<T></code> is a wrapper over <code class="language-plaintext highlighter-rouge">Span<T></code> that enables this to be used in iterator and <code class="language-plaintext highlighter-rouge">async</code> methods.</p>
<p>If you want immutable versions of these, there are <code class="language-plaintext highlighter-rouge">System.ReadOnlySpan<T></code> and <code class="language-plaintext highlighter-rouge">System.ReadOnlyMemory<T></code>. See <a href="https://docs.microsoft.com/en-us/dotnet/api/system.span-1?view=netcore-2.2">Span<T> Struct</a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.memory-1?view=netcore-2.2">Memory<T> Struct</a> documentation for details.</p>
<h2 id="references">References</h2>
<ul>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2">What’s new in C# 7.2</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code">Write safe and efficient C# code</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref">ref (C# Reference)</a></li>
<li><a href="https://blogs.msdn.microsoft.com/seteplia/2018/03/07/the-in-modifier-and-the-readonly-structs-in-c/">The ‘in’-modifier and the readonly structs in C#</a></li>
<li>StackOverflow threads - <a href="https://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net">1</a> , <a href="https://stackoverflow.com/questions/14147340/immutable-class-vs-struct">2</a>, <a href="https://stackoverflow.com/questions/7484735/c-struct-vs-class-faster">3</a>, <a href="https://stackoverflow.com/questions/1951186/which-is-best-for-data-store-struct-classes">4</a>, <a href="https://stackoverflow.com/questions/521298/when-to-use-struct">5</a></li>
<li><a href="https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/readonly-ref.md">Readonly reference docs</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters">Passing Parameters</a></li>
<li><a href="https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/">The Stack Is An Implementation Detail, Part One</a></li>
<li><a href="https://blogs.msdn.microsoft.com/mazhou/2018/03/25/c-7-series-part-10-spant-and-universal-memory-management/">C# 7 Series</a></li>
<li><a href="https://msdn.microsoft.com/en-us/magazine/mt814808.aspx">C# - All About Span: Exploring a New .NET Mainstay</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.span-1?view=netcore-2.2">Span<T> Struct</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.memory-1?view=netcore-2.2">Memory<T> Struct</a></li>
</ul>A quick guide to safe & efficient enhancement of struct or value types in C# 7.2 and 7.3C# 7 features with minor version updates - C# 7.1, C# 7.2, C# 7.32018-12-10T00:00:00+00:002018-12-10T00:00:00+00:00https://arghya.xyz/articles/c-sharp-7-minor-versions<h1 id="a-quick-look-at-the-new-capabilities-of-c-language-with-minor-updates-71-to-73">A quick look at the new capabilities of C# language with minor updates 7.1 to 7.3</h1>
<p><strong><em>This is mostly a bunch of code demos, not so much into the theories.</em></strong></p>
<p>If you are already familiar with <code class="language-plaintext highlighter-rouge">C# 6</code> and <code class="language-plaintext highlighter-rouge">C# 7</code>, this will help you catch up quickly on the new features of the programming language that were introduced with minor versions 7.1 - 7.3, and get you ready for upcoming <a href="https://blogs.msdn.microsoft.com/dotnet/2018/12/05/take-c-8-0-for-a-spin/">C# 8</a>. <strong>If you are not comfortable with <code class="language-plaintext highlighter-rouge">C# 6</code> or <code class="language-plaintext highlighter-rouge">C# 7</code> yet, go and read the <a href="/articles/new-features-of-csharp-6">C# 6</a> and <a href="/articles/new-features-of-csharp-7">C# 7</a> articles first.</strong> Note that the feature list here is not exhaustive, it covers some of the most popular and useful ones. For more details, check reference section at the bottom.</p>
<p class="notice--info"><strong>Note:</strong> This is the first time C# team introduced minor versions, they are not enabled in Visual Studio by default. So if you try the following code, they may not run. To use minor versions of C#, you need to configure your system as explained <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version">here</a>. The easiest is to set that in Visual Studio, per project. Right-click the project on solution explorer, select properties -> Build -> Advanced. In language version dropdown, select “C# latest minor version (latest)”.</p>
<p><img src="/images/posts/misc/csharp-version-in-vs.png" alt="Image" /></p>
<h2 id="c-71-features">C# 7.1 features</h2>
<h4 id="async-in-main"><code class="language-plaintext highlighter-rouge">async</code> in <code class="language-plaintext highlighter-rouge">Main()</code></h4>
<p>Now the entry point method <code class="language-plaintext highlighter-rouge">Main()</code> in your project can also have <code class="language-plaintext highlighter-rouge">async</code> modifier and so can use <code class="language-plaintext highlighter-rouge">await</code> in the method body. If you are not comfortable with <code class="language-plaintext highlighter-rouge">async-await</code>, you can learn about them <a href="/articles/async-await">here</a>.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="k">async</span> <span class="n">Task</span><span class="p"><</span><span class="kt">string</span><span class="p">></span> <span class="nf">Main</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">//Directly await an await-able async method</span>
<span class="k">return</span> <span class="k">await</span> <span class="nf">GetBigMessageAsync</span><span class="p">();</span>
<span class="c1">//or do other stuffs before returning, as required</span>
<span class="p">}</span>
</code></pre></div></div>
<p>If the Main method does not return anything, you can use <code class="language-plaintext highlighter-rouge">async Task Main()</code>.</p>
<h4 id="default-literal"><code class="language-plaintext highlighter-rouge">default</code> literal</h4>
<p>When setting the default value of any type, you can simply use <code class="language-plaintext highlighter-rouge">default</code> literal, without specifying the type.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//Rather than</span>
<span class="n">Dictionary</span><span class="p"><</span><span class="kt">string</span><span class="p">,</span> <span class="n">Func</span><span class="p"><</span><span class="kt">int</span><span class="p">,</span> <span class="kt">bool</span><span class="p">>></span> <span class="n">funcIndex</span> <span class="p">=</span> <span class="k">default</span><span class="p">(</span><span class="n">Dictionary</span><span class="p"><</span><span class="kt">string</span><span class="p">,</span> <span class="n">Func</span><span class="p"><</span><span class="kt">int</span><span class="p">,</span> <span class="kt">bool</span><span class="p">>>);</span>
<span class="c1">//You can now do</span>
<span class="n">Dictionary</span><span class="p"><</span><span class="kt">string</span><span class="p">,</span> <span class="n">Func</span><span class="p"><</span><span class="kt">int</span><span class="p">,</span> <span class="kt">bool</span><span class="p">>></span> <span class="n">funcIndex</span> <span class="p">=</span> <span class="k">default</span><span class="p">;</span>
<span class="c1">//Obviously the following doesn't work</span>
<span class="kt">var</span> <span class="n">inferredVariable</span> <span class="p">=</span> <span class="k">default</span><span class="p">;</span> <span class="c1">//not for implicitly-typed variables</span>
</code></pre></div></div>
<h4 id="inferred-tuple-element-names">Inferred tuple element names</h4>
<p>Now, if you use variables to construct a tuple, by default the tuple elements take the name of those variables.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//let's say you have couple of variables</span>
<span class="kt">int</span> <span class="n">number</span> <span class="p">=</span> <span class="m">5</span><span class="p">;</span>
<span class="kt">bool</span> <span class="n">isEven</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
<span class="c1">//then you use them to construct a tuple</span>
<span class="kt">var</span> <span class="n">numberTypeTuple</span> <span class="p">=</span> <span class="p">(</span><span class="n">number</span><span class="p">,</span> <span class="n">isEven</span><span class="p">);</span> <span class="c1">//automatically named as number, isEven</span>
<span class="kt">var</span> <span class="n">fiveIsEven</span> <span class="p">=</span> <span class="n">numberTypeTuple</span><span class="p">.</span><span class="n">isEven</span><span class="p">;</span> <span class="c1">//works just fine</span>
<span class="c1">//you can still name them explicitly though</span>
<span class="kt">var</span> <span class="n">numberTypeTuple2</span> <span class="p">=</span> <span class="p">(</span><span class="n">Num</span><span class="p">:</span> <span class="n">number</span><span class="p">,</span> <span class="n">IsEven</span><span class="p">:</span> <span class="n">isEven</span><span class="p">);</span> <span class="c1">//explicit names</span>
<span class="kt">var</span> <span class="n">number2</span> <span class="p">=</span> <span class="n">numberTypeTuple2</span><span class="p">.</span><span class="n">Num</span><span class="p">;</span> <span class="c1">//variable names are not used</span>
</code></pre></div></div>
<p>Just remember that, variable names in <code class="language-plaintext highlighter-rouge">Tuple</code> are available only in compile time, they do not exist in runtime.</p>
<h4 id="generic-pattern-matching">Generic pattern matching</h4>
<p>C# 7.1 enhances the pattern matching introduced in <a href="/articles/new-features-of-csharp-7">C# 7</a> to work with generic types. So, now you can pattern-match on generic type arguments.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//Types Cat & Dog implement interface IAnimal</span>
<span class="k">public</span> <span class="kt">string</span> <span class="n">GetSound</span><span class="p"><</span><span class="n">T</span><span class="p">>(</span><span class="n">T</span> <span class="n">animal</span><span class="p">)</span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="n">IAnimal</span>
<span class="p">{</span>
<span class="k">switch</span> <span class="p">(</span><span class="n">animal</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">case</span> <span class="n">Cat</span> <span class="n">cat</span><span class="p">:</span>
<span class="k">return</span> <span class="s">"meow"</span><span class="p">;</span>
<span class="k">case</span> <span class="n">Dog</span> <span class="n">dog</span><span class="p">:</span>
<span class="k">return</span> <span class="s">"bhow"</span><span class="p">;</span>
<span class="k">default</span><span class="p">:</span>
<span class="k">return</span> <span class="s">"..."</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<h2 id="c-72-features">C# 7.2 features</h2>
<h4 id="non-trailing-named-arguments">Non-trailing named arguments</h4>
<p>When you are calling a method with named arguments or optional parameters, it was a rule to have all the named arguments at the end of method signature after all the required arguments.</p>
<p>The compiler could infer the arguments when all are positional (in same order as defined in the method), all are named (so bind arguments by name) or there are required positional arguments followed by named arguments. It was NOT allowed to have a non-named argument after a named argument. This is now supported in C# 7.2, given the compiler can map the arguments by position and/or name. Not a <em>“new”</em> feature as such, but helps write method calls more clearly in some scenarios.</p>
<p>Let’s look at some sample to understand what works & what doesn’t.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">void</span> <span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="kt">int</span> <span class="n">age</span><span class="p">,</span> <span class="kt">string</span> <span class="n">name</span><span class="p">,</span> <span class="kt">bool</span> <span class="n">isAdmin</span> <span class="p">=</span> <span class="k">false</span><span class="p">,</span> <span class="kt">bool</span> <span class="n">isActive</span> <span class="p">=</span> <span class="k">false</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">//use age, name, isAdmin, isActive</span>
<span class="p">}</span>
<span class="k">void</span> <span class="nf">TestMethod</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">//WORKED since C# 4.0</span>
<span class="c1">//standard positional arguments</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="m">30</span><span class="p">,</span> <span class="s">"AC"</span><span class="p">,</span> <span class="k">true</span><span class="p">,</span> <span class="k">true</span><span class="p">);</span>
<span class="c1">//all named & positional - redundant, but more readable</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="n">age</span><span class="p">:</span> <span class="m">30</span><span class="p">,</span> <span class="n">name</span><span class="p">:</span> <span class="s">"AC"</span><span class="p">,</span> <span class="n">isAdmin</span><span class="p">:</span> <span class="k">true</span><span class="p">,</span> <span class="n">isActive</span><span class="p">:</span> <span class="k">false</span><span class="p">);</span>
<span class="c1">//out of position, but all are named - so works</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="s">"AC"</span><span class="p">,</span> <span class="n">age</span><span class="p">:</span> <span class="m">30</span><span class="p">,</span> <span class="n">isActive</span><span class="p">:</span> <span class="k">false</span><span class="p">,</span> <span class="n">isAdmin</span><span class="p">:</span> <span class="k">true</span><span class="p">);</span>
<span class="c1">//same as above, only optional ones are omitted</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="n">age</span><span class="p">:</span> <span class="m">30</span><span class="p">,</span> <span class="n">name</span><span class="p">:</span> <span class="s">"AC"</span><span class="p">);</span>
<span class="c1">//with a (trailing) named argument</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="m">30</span><span class="p">,</span> <span class="s">"AC"</span><span class="p">,</span> <span class="n">isActive</span><span class="p">:</span> <span class="k">false</span><span class="p">);</span>
<span class="c1">//Works ONLY WITH 7.2 and above <<<<</span>
<span class="c1">//isAdmin in non-trailing named argument, but in position/order</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="m">30</span><span class="p">,</span> <span class="s">"AC"</span><span class="p">,</span> <span class="n">isAdmin</span><span class="p">:</span> <span class="k">true</span><span class="p">,</span> <span class="k">true</span><span class="p">);</span>
<span class="c1">//DOES NOT WORK - as mix of named and non-positional arguments</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="s">"AC"</span><span class="p">,</span> <span class="n">age</span><span class="p">:</span> <span class="m">30</span><span class="p">,</span> <span class="k">true</span><span class="p">,</span> <span class="k">true</span><span class="p">);</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="m">30</span><span class="p">,</span> <span class="s">"AC"</span><span class="p">,</span> <span class="n">isActive</span><span class="p">:</span> <span class="k">true</span><span class="p">,</span> <span class="k">true</span><span class="p">);</span>
<span class="nf">FuncWithOptionals</span><span class="p">(</span><span class="m">30</span><span class="p">,</span> <span class="s">"AC"</span><span class="p">,</span> <span class="k">true</span><span class="p">,</span> <span class="n">isAdmin</span><span class="p">:</span> <span class="k">true</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="leading-digit-separator">Leading digit separator</h4>
<p>With <code class="language-plaintext highlighter-rouge">C# 7.0</code>, digit separators were introduced for numeric literals. That means, you could use underscore <code class="language-plaintext highlighter-rouge">_</code> inside numbers to separate digits for better readability. So you could write a million as <code class="language-plaintext highlighter-rouge">1_000_000</code>.</p>
<p><code class="language-plaintext highlighter-rouge">C# 7.2</code> enhances this a bit by allowing digit separator at beginning of numeric literals which can be used with <code class="language-plaintext highlighter-rouge">binary</code> or <code class="language-plaintext highlighter-rouge">hexadecimal</code> for more clarity. Examples below.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//allowed in C# 7.0</span>
<span class="kt">var</span> <span class="n">num</span> <span class="p">=</span> <span class="m">1</span><span class="n">_000_000</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">bin</span> <span class="p">=</span> <span class="m">0</span><span class="n">b0110_1001</span><span class="p">;</span>
<span class="c1">//ONLY allowed in C# 7.2 & above</span>
<span class="kt">var</span> <span class="n">hex</span> <span class="p">=</span> <span class="m">0</span><span class="n">x_89F0A</span><span class="p">;</span>
<span class="kt">var</span> <span class="n">bin2</span> <span class="p">=</span> <span class="m">0</span><span class="n">b_1000_1001</span><span class="p">;</span>
</code></pre></div></div>
<h4 id="private-protected-access-modifier"><code class="language-plaintext highlighter-rouge">private protected</code> access modifier</h4>
<p><code class="language-plaintext highlighter-rouge">C# 7.2</code> introduces a new composite access modifier <code class="language-plaintext highlighter-rouge">private protected</code>, with which members will be accessible only in child classes (through inheritance) in <strong>same assembly</strong>.</p>
<p>We already had a composite access modifier <code class="language-plaintext highlighter-rouge">protected internal</code> which was accessible through EITHER inheritance OR in the same assembly. The new <code class="language-plaintext highlighter-rouge">private protected</code> restricts to ONLY inheritance AND in same assembly.</p>
<p>Let’s look at some code examples for clarity</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//traditional - access through inheritance OR within assembly</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">WithProtectedInternal</span>
<span class="p">{</span>
<span class="k">protected</span> <span class="k">internal</span> <span class="k">void</span> <span class="nf">M</span><span class="p">()</span> <span class="p">{</span> <span class="p">}</span>
<span class="p">}</span>
<span class="c1">//in same assembly, inheritance not required</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">Test2</span>
<span class="p">{</span>
<span class="k">protected</span> <span class="k">void</span> <span class="nf">DoWork</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">new</span> <span class="nf">WithProtectedInternal</span><span class="p">().</span><span class="nf">M</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c1">//another assembly, only through inheritance</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">Test2</span> <span class="p">:</span> <span class="n">WithProtectedInternal</span>
<span class="p">{</span>
<span class="k">protected</span> <span class="k">void</span> <span class="nf">DoWork</span><span class="p">()</span>
<span class="p">{</span>
<span class="nf">M</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c1">//NEW in C# 7.2</span>
<span class="c1">//access through inheritance within same assembly</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">WithPrivateProtected</span>
<span class="p">{</span>
<span class="k">private</span> <span class="k">protected</span> <span class="k">void</span> <span class="nf">M</span><span class="p">()</span> <span class="p">{</span> <span class="p">}</span>
<span class="p">}</span>
<span class="c1">//in same assembly (it's not internal)</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">Test</span> <span class="p">:</span> <span class="n">WithPrivateProtected</span>
<span class="p">{</span>
<span class="k">protected</span> <span class="k">void</span> <span class="nf">DoWork</span><span class="p">()</span>
<span class="p">{</span>
<span class="nf">M</span><span class="p">();</span> <span class="c1">//works</span>
<span class="k">new</span> <span class="nf">WithPrivateProtected</span><span class="p">().</span><span class="nf">M</span><span class="p">();</span> <span class="c1">//does NOT work</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c1">//another assembly - DOES NOT COMPILE</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">Test</span> <span class="p">:</span> <span class="n">WithPrivateProtected</span>
<span class="p">{</span>
<span class="k">protected</span> <span class="k">void</span> <span class="nf">DoWork</span><span class="p">()</span>
<span class="p">{</span>
<span class="nf">M</span><span class="p">();</span> <span class="c1">//inaccessible due to protection level</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="conditional-ref-expression">Conditional <code class="language-plaintext highlighter-rouge">ref</code> expression</h4>
<p>Using <code class="language-plaintext highlighter-rouge">ref</code> you can get <strong>reference</strong> of an expression result rather than the value. For example, you get reference to one item in an array based on some condition. To elaborate, let’s expand on the example from the official <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator#conditional-ref-expression">docs</a>.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">smallArray</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">int</span><span class="p">[]</span> <span class="p">{</span> <span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">,</span> <span class="m">4</span><span class="p">,</span> <span class="m">5</span> <span class="p">};</span>
<span class="kt">var</span> <span class="n">largeArray</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">int</span><span class="p">[]</span> <span class="p">{</span> <span class="m">10</span><span class="p">,</span> <span class="m">20</span><span class="p">,</span> <span class="m">30</span><span class="p">,</span> <span class="m">40</span><span class="p">,</span> <span class="m">50</span> <span class="p">};</span>
<span class="c1">//this is how it already worked till C# 7.1</span>
<span class="kt">int</span> <span class="n">index</span> <span class="p">=</span> <span class="m">7</span><span class="p">;</span>
<span class="kt">int</span> <span class="k">value</span> <span class="p">=</span> <span class="p">((</span><span class="n">index</span> <span class="p"><</span> <span class="m">5</span><span class="p">)</span> <span class="p">?</span> <span class="n">smallArray</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">:</span> <span class="n">largeArray</span><span class="p">[</span><span class="n">index</span> <span class="p">-</span> <span class="m">5</span><span class="p">]);</span>
<span class="k">value</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="c1">//this just updates the copy of value, not largeArray[2]</span>
<span class="c1">//This was not a valid syntax</span>
<span class="c1">//((index < 5) ? smallArray[index] : largeArray[index - 5]) = 100;</span>
<span class="c1">//so there is no change in the original arrays</span>
<span class="kt">var</span> <span class="n">smallArrayStr</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="nf">Join</span><span class="p">(</span><span class="s">" "</span><span class="p">,</span> <span class="n">smallArray</span><span class="p">);</span> <span class="c1">//1 2 3 4 5</span>
<span class="kt">var</span> <span class="n">largeArrayStr</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="nf">Join</span><span class="p">(</span><span class="s">" "</span><span class="p">,</span> <span class="n">largeArray</span><span class="p">);</span> <span class="c1">// 10 20 30 40 50</span>
<span class="c1">//>>>> NEW in C# 7.2, you can get a reference to original item <<<<</span>
<span class="k">ref</span> <span class="kt">int</span> <span class="n">refValue</span> <span class="p">=</span> <span class="k">ref</span> <span class="p">((</span><span class="n">index</span> <span class="p"><</span> <span class="m">5</span><span class="p">)</span> <span class="p">?</span> <span class="k">ref</span> <span class="n">smallArray</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">:</span> <span class="k">ref</span> <span class="n">largeArray</span><span class="p">[</span><span class="n">index</span> <span class="p">-</span> <span class="m">5</span><span class="p">]);</span>
<span class="n">refValue</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="c1">//here, actually largeArray[2] got updated to 0!</span>
<span class="c1">//and this is a valid syntax, that updates smallArray[2] to 100!</span>
<span class="n">index</span> <span class="p">=</span> <span class="m">2</span><span class="p">;</span>
<span class="p">((</span><span class="n">index</span> <span class="p"><</span> <span class="m">5</span><span class="p">)</span> <span class="p">?</span> <span class="k">ref</span> <span class="n">smallArray</span><span class="p">[</span><span class="n">index</span><span class="p">]</span> <span class="p">:</span> <span class="k">ref</span> <span class="n">largeArray</span><span class="p">[</span><span class="n">index</span> <span class="p">-</span> <span class="m">5</span><span class="p">])</span> <span class="p">=</span> <span class="m">100</span><span class="p">;</span>
<span class="c1">//so we get...</span>
<span class="n">smallArrayStr</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="nf">Join</span><span class="p">(</span><span class="s">" "</span><span class="p">,</span> <span class="n">smallArray</span><span class="p">);</span> <span class="c1">//1 2 100 4 5</span>
<span class="n">largeArrayStr</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="nf">Join</span><span class="p">(</span><span class="s">" "</span><span class="p">,</span> <span class="n">largeArray</span><span class="p">);</span> <span class="c1">// 10 20 0 40 50</span>
</code></pre></div></div>
<h3 id="safe-efficient-enhancements-to-value-type">Safe efficient enhancements to value type</h3>
<p>C# 7.2 introduces a bunch of features which work together towards the same goal - making value types efficient & safe to work with. We discuss those features separately in the post <strong><a href="/articles/c-sharp-7.2-value-type-enhancements/">C# 7.2 value type enhancements</a></strong>.</p>
<h2 id="c-73-features">C# 7.3 features</h2>
<p>This minor version update on the language does not bring any <em>“new”</em> feature as such. Rather <code class="language-plaintext highlighter-rouge">C# 7.3</code> goes in the same direction of <code class="language-plaintext highlighter-rouge">C# 7.2</code> and adds some more features for safe & efficient code. It also adds some enhancement to some existing features. We’ll briefly look at only couple of those features, see the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3">official docs</a> for all the features.</p>
<h4 id="reassignment-of-ref-local-variables">Reassignment of <code class="language-plaintext highlighter-rouge">ref local</code> variables</h4>
<p>Before <code class="language-plaintext highlighter-rouge">C# 7.3</code>, once a <code class="language-plaintext highlighter-rouge">ref local</code> variable has been declared and initialized, it could not be re-assignd to another ref local. It’s now supported.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//a simple ref return method</span>
<span class="k">ref</span> <span class="kt">int</span> <span class="nf">GetPrevious</span><span class="p">(</span><span class="kt">int</span><span class="p">[]</span> <span class="n">arr</span><span class="p">,</span> <span class="kt">int</span> <span class="n">idx</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">arr</span> <span class="p">==</span> <span class="k">null</span> <span class="p">||</span> <span class="n">idx</span> <span class="p"><=</span> <span class="m">0</span><span class="p">)</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentException</span><span class="p">();</span>
<span class="k">return</span> <span class="k">ref</span> <span class="n">arr</span><span class="p">[</span><span class="n">idx</span> <span class="p">-</span> <span class="m">1</span><span class="p">];</span>
<span class="p">}</span>
<span class="c1">//another ref return method</span>
<span class="k">ref</span> <span class="kt">int</span> <span class="nf">GetNext</span><span class="p">(</span><span class="kt">int</span><span class="p">[]</span> <span class="n">arr</span><span class="p">,</span> <span class="kt">int</span> <span class="n">idx</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">arr</span> <span class="p">==</span> <span class="k">null</span> <span class="p">||</span> <span class="n">idx</span> <span class="p">>=</span> <span class="n">arr</span><span class="p">.</span><span class="n">Length</span> <span class="p">-</span> <span class="m">1</span><span class="p">)</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nf">ArgumentException</span><span class="p">();</span>
<span class="k">return</span> <span class="k">ref</span> <span class="n">arr</span><span class="p">[</span><span class="n">idx</span> <span class="p">+</span> <span class="m">1</span><span class="p">];</span>
<span class="p">}</span>
<span class="c1">//actual usage</span>
<span class="k">void</span> <span class="nf">TestRefReturn</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">arr</span> <span class="p">=</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">,</span> <span class="m">4</span><span class="p">,</span> <span class="m">5</span> <span class="p">};</span>
<span class="k">ref</span> <span class="kt">int</span> <span class="n">arrItem</span> <span class="p">=</span> <span class="k">ref</span> <span class="nf">GetPrevious</span><span class="p">(</span><span class="n">arr</span><span class="p">,</span> <span class="m">2</span><span class="p">);</span>
<span class="c1">//ONLY works with C# 7.3 and above</span>
<span class="n">arrItem</span> <span class="p">=</span> <span class="k">ref</span> <span class="nf">GetNext</span><span class="p">(</span><span class="n">arr</span><span class="p">,</span> <span class="m">2</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="enhanced-generic-constraints">Enhanced generic constraints</h4>
<p>Now <code class="language-plaintext highlighter-rouge">System.Enum</code> & <code class="language-plaintext highlighter-rouge">System.Delegate</code> can be used as type constraint on generic types. From the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint">official docs</a>, these are now valid generic constraints.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">UsingEnum</span><span class="p"><</span><span class="n">T</span><span class="p">></span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Enum</span> <span class="p">{</span> <span class="p">}</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">UsingDelegate</span><span class="p"><</span><span class="n">T</span><span class="p">></span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Delegate</span> <span class="p">{</span> <span class="p">}</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">Multicaster</span><span class="p"><</span><span class="n">T</span><span class="p">></span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">MulticastDelegate</span> <span class="p">{</span> <span class="p">}</span>
</code></pre></div></div>
<h4 id="tuple-enhancements">Tuple enhancements</h4>
<p>Tuples can now be equated with <code class="language-plaintext highlighter-rouge">==</code> and <code class="language-plaintext highlighter-rouge">!=</code>, the comparison will work on each of the tuple members. It can also work if one side is nullable while the other is not. It even does <em>implicit conversion</em> of member types when comparable types are found (see example below).</p>
<p>But remember that the tuple variable names exist only at compile time, not at run time. At run time, the variables are still referred as <code class="language-plaintext highlighter-rouge">Item1</code>, <code class="language-plaintext highlighter-rouge">Item2</code> etc. So the variable names really does not matter as long as the sequence of members have same type. If the sequence does not match, tuples will not match even if variable names are same.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">internal</span> <span class="k">void</span> <span class="nf">TestTupleEquality</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">t1</span> <span class="p">=</span> <span class="p">(</span><span class="n">A</span><span class="p">:</span> <span class="m">1</span><span class="p">,</span> <span class="n">B</span><span class="p">:</span> <span class="s">"hello"</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">t2</span> <span class="p">=</span> <span class="p">(</span><span class="n">A</span><span class="p">:</span> <span class="m">1</span><span class="p">,</span> <span class="n">B</span><span class="p">:</span> <span class="s">"hello"</span><span class="p">);</span>
<span class="c1">//making it nullable</span>
<span class="p">(</span><span class="kt">int</span> <span class="n">A</span><span class="p">,</span> <span class="kt">string</span> <span class="n">B</span><span class="p">)?</span> <span class="n">t3</span> <span class="p">=</span> <span class="n">t2</span><span class="p">;</span>
<span class="c1">//with compatible but not same type</span>
<span class="p">(</span><span class="kt">long</span> <span class="n">A</span><span class="p">,</span> <span class="kt">string</span> <span class="n">B</span><span class="p">)</span> <span class="n">t4</span> <span class="p">=</span> <span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="s">"hello"</span><span class="p">);</span>
<span class="c1">//with different tuple variable names</span>
<span class="kt">var</span> <span class="n">t5</span> <span class="p">=</span> <span class="p">(</span><span class="n">X</span><span class="p">:</span> <span class="m">1</span><span class="p">,</span> <span class="n">Y</span><span class="p">:</span> <span class="s">"hello"</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">test1</span> <span class="p">=</span> <span class="n">t1</span> <span class="p">==</span> <span class="n">t2</span><span class="p">;</span> <span class="c1">//true</span>
<span class="kt">var</span> <span class="n">test2</span> <span class="p">=</span> <span class="n">t1</span> <span class="p">==</span> <span class="n">t3</span><span class="p">;</span> <span class="c1">//true</span>
<span class="kt">var</span> <span class="n">test3</span> <span class="p">=</span> <span class="n">t1</span> <span class="p">==</span> <span class="n">t4</span><span class="p">;</span> <span class="c1">//true</span>
<span class="kt">var</span> <span class="n">test4</span> <span class="p">=</span> <span class="n">t1</span> <span class="p">==</span> <span class="n">t5</span><span class="p">;</span> <span class="c1">//true</span>
<span class="c1">//this DOES NOT WORK for type (sequence) mismatch</span>
<span class="kt">var</span> <span class="n">t6</span> <span class="p">=</span> <span class="p">(</span><span class="n">B</span><span class="p">:</span> <span class="s">"hello"</span><span class="p">,</span> <span class="n">A</span><span class="p">:</span> <span class="m">1</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>If you haven’t already, read about the <strong><a href="/articles/c-sharp-7.2-value-type-enhancements/">C# 7.2 value type enhancements</a></strong>.</p>
<h2 id="references">References</h2>
<ul>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1">What’s new in C# 7.1</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2">What’s new in C# 7.2</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3">What’s new in C# 7.3</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code">Write safe and efficient C# code</a></li>
<li><a href="https://blogs.msdn.microsoft.com/mazhou/2018/03/25/c-7-series-part-10-spant-and-universal-memory-management/">C# 7 Series - Mark Zhou’s Tech Blog</a></li>
</ul>A quick guide to new features introduced to C# in minor versions 7.1 to 7.3Hosting an ASP.NET Core web application on Windows IIS2018-09-12T00:00:00+00:002018-09-12T00:00:00+00:00https://arghya.xyz/articles/aspnetcore-on-windows-iis<p>In this post, we’ll see how to host your brand new shiny <code class="language-plaintext highlighter-rouge">ASP.NET Core</code> web application on a Windows <code class="language-plaintext highlighter-rouge">IIS</code> server, so that it can be used at production level.</p>
<p>We’ll not cover anything about .NET Core development, or about IIS as a general purpose web server on <code class="language-plaintext highlighter-rouge">Windows</code> computers. If you have already created some ASP.NET Core application and run them locally (e.g. from Visual Studio), and you have some familiarity with IIS, this post will show you how to quickly host your ASP.NET Core application on IIS. The purpose of existence of this post is, the deployment process is different from that of full .NET Framework applications. Along the way, we’ll cover some basic concepts and explain few things in brief.</p>
<p>If you are not looking for hosting your application on Windows IIS, head over to this <a href="https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/?view=aspnetcore-2.1&tabs=aspnetcore2x">official documentation</a> to learn how to host it on <code class="language-plaintext highlighter-rouge">Linux</code>, <code class="language-plaintext highlighter-rouge">MacOS</code>, <code class="language-plaintext highlighter-rouge">Docker</code> or <code class="language-plaintext highlighter-rouge">Azure</code>. If you want to learn about .NET Core, check out this series on <strong><a href="/articles/dotnet-core-2.0/">Working with .NET Core 2.0</a></strong>.</p>
<p class="notice--success"><strong>TL;DR</strong> If you already know how to host a website on IIS and the deployment options for .NET Core applications (FDD & SCD), the most important step for hosting ASP.NET Core applications on IIS server is that, you’ll need to install the <strong><code class="language-plaintext highlighter-rouge">ASP.NET Core IIS Module</code></strong>.</p>
<p>Just before we jump in, one might be wondering, when ASP.NET Core application already comes with its own web server <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/?view=aspnetcore-2.1&tabs=aspnetcore2x">Kestrel</a>, why would anyone host it on IIS! Kestrel is very lean (and fast), and does only what is required, i.e. serve a HTTP request with a response. On the other hand, mature web servers like <code class="language-plaintext highlighter-rouge">IIS</code>, <code class="language-plaintext highlighter-rouge">Nginx</code>, <code class="language-plaintext highlighter-rouge">Apache</code> etc. have much more functionality built into them. So, it is always advised to use Kestrel behind a full web server as <em>reverse proxy</em>, for production use. That means, the web server will receive the request from internet, and forward it to Kestrel after some general preliminary work and send the response back from Kestrel.</p>
<p><img src="/images/posts/misc/kestrel-to-internet.png" alt="Image" /></p>
<p>With a full web server, viz. IIS, you can do stuffs that are not possible with Kestrel. Some examples are - running multiple apps on same server sharing same port (e.g. mysite.com and othersite.com both listening to HTTP port 80), public domain & SSL certificate management, security & authentication, request limiting, caching, URL re-writing etc.</p>
<hr />
<p>The basic steps to host an ASP.NET Core application on IIS are</p>
<ol>
<li>Publish or package your application</li>
<li>Install/Enable the IIS server</li>
<li>Install .NET Core Runtime & Hosting Bundle</li>
<li>Create a new website for your application</li>
<li>Configure</li>
</ol>
<h4 id="1-package-your-application">[1] Package your application</h4>
<p>Build your application. Once successfully built, publish your ASP.NET Core web application. The 2 basic ways to <strong>publish</strong> are</p>
<ol>
<li>Right-click the project in <code class="language-plaintext highlighter-rouge">Visual Studio</code> and select publish</li>
<li>Use the <code class="language-plaintext highlighter-rouge">dotnet CLI</code> command for <a href="https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish?tabs=netcore21">publish</a>, i.e. <code class="language-plaintext highlighter-rouge">dotnet publish</code></li>
</ol>
<p>Whichever way you prefer among the two above, there are 2 types of deployment</p>
<ol>
<li><strong><a href="https://docs.microsoft.com/en-us/dotnet/core/deploying/#framework-dependent-deployments-fdd">FDD</a></strong> or Framework-Dependent Deployment. Here, only your app, NuGet and other related packages & configurations are packed in the published package. It needs the .NET Core runtime to be present on the target machine to run. The published package is platform independent and can run on any supported platform like <code class="language-plaintext highlighter-rouge">Windows</code>, <code class="language-plaintext highlighter-rouge">Linux</code> or <code class="language-plaintext highlighter-rouge">MacOS</code>. Practically, FDD also has options like
<ol>
<li><strong>Portable</strong> - totally platform independent (there are some catch though, see later). Total binary size is pretty small, comes with your own DLLs, some .NET Core base types and a few specific to different runtimes</li>
<li><strong>Runtime specific</strong> - not the ideal framework dependent, and comes with bunch of runtime specific files (that can avoid the catch situations of portable option above). Binary size much larger than the portable one</li>
</ol>
</li>
<li><strong><a href="https://docs.microsoft.com/en-us/dotnet/core/deploying/#self-contained-deployments-scd">SCD</a></strong> or Self-Contained Deployment. Here the whole (the required parts) .NET Core runtime and <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.1">Kestrel</a> web server is packed with your application code. So, you can directly deploy the package on a machine and run, it does not need the .NET Core runtime to be pre-installed on the machine. This is a platform specific deployment, so you must choose the target runtime at the time of publish e.g. <code class="language-plaintext highlighter-rouge">win-x64</code> or <code class="language-plaintext highlighter-rouge">linux-x64</code>. The binary size much larger compared those FDD options.</li>
</ol>
<p>If you are deploying on Windows-IIS, generally you’ll have the .NET Core installed, so you can publish your applications as <code class="language-plaintext highlighter-rouge">FDD win-x64</code>, so that published binaries are not very large and also you avoid some issues with portable deployment.</p>
<p class="notice--info"><strong>Note:</strong> In .NET Core, you specify a target platform with a <code class="language-plaintext highlighter-rouge">runtime ID</code>. A runtime ID is nothing but a combination of a specific OS and processor architecture e.g. win-x86, linux-x64 or osx-x64.</p>
<p class="notice--info"><strong>Note:</strong> Actual size of the published binaries will vary based on the type, size & complexity of the project. And they’ll also change, probably, with future releases of .NET Core. But, just to give an idea, for one of my not-so-large ASP.NET Core MVC project with .NET Core 2.0, the sizes are - 10 MB (FDD Portable), 40 MB (FDD Win-x64) and 100 MB (SCD Win-x64).</p>
<h4 id="2-setup-iis-web-server">[2] Setup IIS web server</h4>
<p>Now you need IIS web server up & running on your Windows desktop or server. If you already have a running IIS, skip this step. Then you need to have <code class="language-plaintext highlighter-rouge">ASP.NET Core Module</code> installed on the system, that comes as part of the <em>.NET Core Runtime & Hosting Bundle</em>.</p>
<p>Install the IIS. IIS comes as part of Windows OS, so you basically need to enable them. Follow instructions from <a href="https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.1&tabs=aspnetcore2x#iis-configuration">here</a> and enable it from Windows features in Control Panel. Note that, you’ll need to have <strong>Administrator role</strong> to install and configure IIS.</p>
<h4 id="3-install-net-core-runtime--hosting-bundle">[3] Install .NET Core Runtime & Hosting Bundle</h4>
<p>Now we’ll need the <strong><code class="language-plaintext highlighter-rouge">ASP.NET Core IIS Module</code></strong> configured for IIS, which comes as part of <em>.NET Core Hosting Bundle</em>. This enables IIS to serve ASP.NET Core applications. Remember that ASP.NET Core web applications run as separate process with Kestrel web server. IIS needs this module to handle this setup.</p>
<ol>
<li>Next we’ll get <em>.NET Core Hosting Bundle</em>, which needs <em>Microsoft Visual C++</em> to run. It’ll be auto downloaded during installation. But, if you are working on a machine that does not have active internet connection, you first need to install it separately. So, if you have active internet on target machine, skip step 1 & 2. Go to the download the latest version (<code class="language-plaintext highlighter-rouge">x64</code> or <code class="language-plaintext highlighter-rouge">x86</code>) of <a href="https://support.microsoft.com/en-in/help/2977003/the-latest-supported-visual-c-downloads">Microsoft Visual C++ latest Redistributable</a>.</li>
<li>Install the Microsoft Visual C++ latest Redistributable package downloaded, double click on installer or run from command prompt.</li>
<li>Now, we’ll install the <em>.NET Core Hosting Bundle</em>. Go to <a href="https://www.microsoft.com/net/download">.NET Downloads</a> page. Click <em>Download .NET Core Runtime</em>, under <code class="language-plaintext highlighter-rouge">.NET Core</code> menu. It’ll download the required installers.</li>
<li>Install the Microsoft .NET Core Hosting Bundle. To avoid installing the x86 components on a x64 machine, run the installer from command prompt with <code class="language-plaintext highlighter-rouge">OPT_NO_X86</code> switch e.g.</li>
</ol>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="s">C:\Dir_with_installer> dotnet-hosting-2.1.4-win.exe OPT_NO_X86=1</span>
</code></pre></div></div>
<p>Now, restart the system or restart IIS so that the ASP.NET Core module is recognized by IIS. You can do that without system restart with following commands in admin mode - <code class="language-plaintext highlighter-rouge">net stop was /y</code> followed by <code class="language-plaintext highlighter-rouge">net start w3svc</code>. It’ll show messages similar to following.</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="s">c:\SomeDirectory>net stop was /y</span>
<span class="s">The following services are dependent on the Windows Process Activation Service service.</span>
<span class="s">Stopping the Windows Process Activation Service service will also stop these services.</span>
<span class="s">World Wide Web Publishing Service</span>
<span class="s">The World Wide Web Publishing Service service is stopping.</span>
<span class="s">The World Wide Web Publishing Service service was stopped successfully.</span>
<span class="s">The Windows Process Activation Service service is stopping.</span>
<span class="s">The Windows Process Activation Service service was stopped successfully.</span>
<span class="s">c:\SomeDirectory>net start w3svc</span>
<span class="s">The World Wide Web Publishing Service service is starting.</span>
<span class="s">The World Wide Web Publishing Service service was started successfully.</span>
</code></pre></div></div>
<p>Just in case you thought what is this <em>.NET Core Hosting Bundle</em> that you just installed, the download page says it clearly.</p>
<blockquote>
<p>The .NET Core Runtime & Hosting Bundle contains everything you need to run existing .NET Core apps, including hosting ASP.NET Core apps. The bundle includes the .NET Core runtime, the ASP.NET Core runtime, and if installed on a machine with IIS it will also add the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-module?view=aspnetcore-2.1">ASP.NET Core IIS Module</a>.</p>
</blockquote>
<p>Now you might be wondering, if you published your application as SCD, why do you need this ASP.NET Core runtime? Shouldn’t you package be self-sufficient? The answer is yes, you app can run on its own (with Kestrel on Windows and with Kestrel/other web servers on other OS). But this runtime and module is required by IIS so that it can host your ASP.NET Core application, which was originally built to host full .NET Framework ASP.NET applications.</p>
<h4 id="4-create-a-new-website-on-iis">[4] Create a new website on IIS</h4>
<p>If you have hosted any ASP.NET application on IIS before, you already know how to create a new website. If you have not done it before, follow step by step instructions from <a href="https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.1&tabs=aspnetcore2x#create-the-iis-site">here</a>.</p>
<p>Here, we’ll quickly create a new website on IIS for our application and do so minimal configuration.</p>
<ol>
<li>Open IIS. Search for IIS or run <code class="language-plaintext highlighter-rouge">inetmgr</code> from run command (Windows + R). Remember you need to be an admin on the system to access IIS.</li>
<li>Under the server node on the left, right-click on <code class="language-plaintext highlighter-rouge">Sites</code> and select <code class="language-plaintext highlighter-rouge">Add Website</code>. Give the site a name (e.g. mycoreweb.com), use the same name for <code class="language-plaintext highlighter-rouge">host</code> and select the directory where the app is published as <code class="language-plaintext highlighter-rouge">Physical path</code>.</li>
<li>It’ll also create a new <code class="language-plaintext highlighter-rouge">app_pool</code> with the same name as the website host. You can use the same, select a different one or rename it if you want. It’s important you configure your application pool and set <em>pipeline mode = Integrated</em>, <em><strong>.NET CLR Version = No Managed Code</strong></em>. This basically tells the IIS it need not load full .NET Framework CLR, and the application will run on it’s own process. This is optional though.</li>
<li>If you just want to host a web app quickly and test on a dev machine, rather than step [2] it <em>might</em> be easier to just <code class="language-plaintext highlighter-rouge">Add Application</code> on the <code class="language-plaintext highlighter-rouge">Sites > Default Web Site</code>. If you give it a name like <code class="language-plaintext highlighter-rouge">mysite</code>, locally you can access this as <code class="language-plaintext highlighter-rouge">http://localhost/mysite</code> on the browser.</li>
</ol>
<p>Make sure your app_pool and the website are running, and you can browse your ASP.NET Core application now. See below for more configuration options.</p>
<h4 id="5-configure">[5] Configure</h4>
<p>You should already have a running application, but few more configuration will help you manage & troubleshoot your application.</p>
<p>ASP.NET Core applications do not have a <code class="language-plaintext highlighter-rouge">web.config</code> (to know about configuration in .NET Core applications, read <a href="/articles/practical-configuration-and-di-in-aspnet-core/">this</a>), but when you publish it for Windows, a web.config gets generated. This is required by IIS and it has some minimal configuration.</p>
<p>It’s good you enable <strong>logs</strong>. Then it’ll create simple text logs for events like application start-up and errors, comes handy when trying to find problems. To enable logging</p>
<ol>
<li>Create a <code class="language-plaintext highlighter-rouge">logs</code> directory in the application root i.e. in the published folder that IIS points to. This directory will host the ASP.NET Core Module stdout logs when stdout logging is enabled (see config below)</li>
<li>Turn on the logs by changing this flag <code class="language-plaintext highlighter-rouge">stdoutLogEnabled="true"</code> in web.config</li>
</ol>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp"><?xml version="1.0" encoding="utf-8"?></span>
<span class="nt"><configuration></span>
<span class="nt"><system.webServer></span>
<span class="nt"><handlers></span>
<span class="nt"><add</span> <span class="na">name=</span><span class="s">"aspNetCore"</span> <span class="na">path=</span><span class="s">"*"</span> <span class="na">verb=</span><span class="s">"*"</span> <span class="na">modules=</span><span class="s">"AspNetCoreModule"</span> <span class="na">resourceType=</span><span class="s">"Unspecified"</span> <span class="nt">/></span>
<span class="nt"></handlers></span>
<span class="nt"><aspNetCore</span> <span class="na">processPath=</span><span class="s">"dotnet"</span> <span class="na">arguments=</span><span class="s">".\Web.Project.dll"</span> <span class="na">stdoutLogEnabled=</span><span class="s">"true"</span> <span class="na">stdoutLogFile=</span><span class="s">".\logs\stdout"</span> <span class="nt">/></span>
<span class="nt"></system.webServer></span>
<span class="nt"></configuration></span>
</code></pre></div></div>
<p>This is a FDD config, so the <code class="language-plaintext highlighter-rouge">processPath</code> points to the <code class="language-plaintext highlighter-rouge">dotnet.exe</code> that’ll run the process, and host the main web dll (e.g. Web.Project.dll). On the other hand, for SCD on Windows, it’ll create an executable for the main web (e.g. Web.Project.exe) and that’ll be the target process.</p>
<p>NOTE: When built with version <code class="language-plaintext highlighter-rouge">ASP.NET Core 3.1.3</code> (April 2020), other changes are not required, just enable the logging with <code class="language-plaintext highlighter-rouge">stdoutLogEnabled="true"</code>.</p>
<p>See the last section <em>“Accessing the website locally and on network”</em> if you are having trouble accesing the page from browser.</p>
<hr />
<h4 id="some-common-problems">Some common problems</h4>
<p>[1] If you get <strong>HTTP Error 502.5 - Process Failure</strong> that basically means IIS could not start the process, for which most common reason is - it could not find .NET Core executable (discussed just above). To fix this, the options are</p>
<ol>
<li>Add the .NET Core path to system environment PATH (e.g. C:\ProgramFiles\dotnet)</li>
<li>Mention the full path to <code class="language-plaintext highlighter-rouge">dotnet.exe</code> in (for FDD) or <code class="language-plaintext highlighter-rouge">.\Web.Project.exe</code> (for SCD) in <code class="language-plaintext highlighter-rouge">aspNetCore processPath</code> attribute of <code class="language-plaintext highlighter-rouge">web.config</code></li>
</ol>
<p>[2] If you get an error that says <strong>dependencies manifest was not found</strong>, that means, well as it says. Some manifest files are missing that is used by the system. The error might look like this</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">Error</span><span class="pi">:</span>
<span class="s">An assembly specified in the application dependencies manifest (Web.Project.deps.json) was not found</span><span class="pi">:</span>
<span class="na">package</span><span class="pi">:</span> <span class="s1">'</span><span class="s">Microsoft.ApplicationInsights.AspNetCore'</span><span class="err">,</span> <span class="na">version</span><span class="pi">:</span> <span class="s1">'</span><span class="s">2.1.1'</span>
<span class="na">path</span><span class="pi">:</span> <span class="s1">'</span><span class="s">lib/netstandard1.6/Microsoft.ApplicationInsights.AspNetCore.dll'</span>
<span class="na">This assembly was expected to be in the local runtime store as the application was published using the following target manifest files</span><span class="pi">:</span>
<span class="s">aspnetcore-store-2.0.0-linux-x64.xml;aspnetcore-store-2.0.0-osx-x64.xml;aspnetcore-store-2.0.0-win7-x64.xml;aspnetcore-store-2.0.0-win7-x86.xml</span>
</code></pre></div></div>
<p>This <a href="https://stackoverflow.com/questions/46491957/asp-net-core-2-missing-applicationinsights">SO post</a> and this <a href="https://github.com/dotnet/coreclr/issues/13542">GitHub issue</a> talks about the problem. To fix this, you have to either of the following three options</p>
<ol>
<li>Install .NET Core full <a href="https://www.microsoft.com/net/download/archives">SDK</a> (not just the runtime) on the server</li>
<li>If it is a Framework Dependent Deployment, publish your app with specific runtime ID (e.g. win-x64 or linux-x64) rather than <em>“Portable”</em> (the <em>catch</em> mentioned above)</li>
<li>Add this flag to your main <code class="language-plaintext highlighter-rouge">web.csproj</code> and publish</li>
</ol>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><PropertyGroup></span>
...
<span class="nt"><PublishWithAspNetCoreTargetManifest></span>false<span class="nt"></PublishWithAspNetCoreTargetManifest></span>
<span class="nt"></PropertyGroup></span>
</code></pre></div></div>
<p>[3] If you get <strong>HTTP Error 500.31 - ANCM Failed to Find Native Dependencies</strong>, that might be because of multiple reasons. And the error text is generally not very helpful (for me, it said <em>“The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found”</em>).</p>
<p><img src="/images/posts/misc/iis-error-500-31-2.png" alt="Image" /></p>
<p>In my case, it happened when migrating to <code class="language-plaintext highlighter-rouge">ASP.NET Core Runtime 3.1.3</code>! It’s weird and hard to find the cause. As suggested in this <a href="https://stackoverflow.com/questions/56630477/http-error-500-31-ancm-failed-to-find-native-dependencies-in-iis">SO post</a> and <a href="https://github.com/OrchardCMS/OrchardCore/issues/4721">GitHub issue</a>, the fix is simple though. In the generated <code class="language-plaintext highlighter-rouge">web.config</code> file, the handler line might have <code class="language-plaintext highlighter-rouge">modules="AspNetCoreModuleV2"</code>. Just remove <code class="language-plaintext highlighter-rouge">V2</code> from it.</p>
<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt"><handlers></span>
<span class="nt"><add</span> <span class="na">name=</span><span class="s">"aspNetCore"</span> <span class="na">path=</span><span class="s">"*"</span> <span class="na">verb=</span><span class="s">"*"</span> <span class="na">modules=</span><span class="s">"AspNetCoreModule"</span> <span class="na">resourceType=</span><span class="s">"Unspecified"</span> <span class="nt">/></span>
<span class="nt"></handlers></span>
</code></pre></div></div>
<p>[4] Some other common problems with fix suggestions are listed <a href="https://docs.microsoft.com/en-us/aspnet/core/test/troubleshoot-azure-iis?view=aspnetcore-3.1">here</a></p>
<p>[5] Also good to know, standard <code class="language-plaintext highlighter-rouge">IIS Logs</code> are available at following locations</p>
<ol>
<li><code class="language-plaintext highlighter-rouge">%SystemDrive%\inetpub\logs\LogFiles</code></li>
<li><code class="language-plaintext highlighter-rouge">%SystemDrive%\Windows\System32\LogFiles\HTTPERR</code></li>
<li>In the Event Viewer, check this custom view to easily locate IIS event logs: <code class="language-plaintext highlighter-rouge">Event Viewer</code> > <code class="language-plaintext highlighter-rouge">Custom Views</code> > <code class="language-plaintext highlighter-rouge">ServerRoles</code> > <code class="language-plaintext highlighter-rouge">Web Server</code></li>
</ol>
<hr />
<h4 id="accessing-the-website-locally-and-on-network">Accessing the website locally and on network</h4>
<p>This is not related to .NET Core, but if you are struggling to access your IIS hosted website on the same machine or over the LAN, you need to set the bindings properly and tweak the <code class="language-plaintext highlighter-rouge">hosts</code> file.</p>
<p>The hosts file bit is only required if you’re trying to access the website with a custom domain name like <em>mycoolsite.com</em>. The hosts file works like the first level DNS lookup, so you can setup any domain name to IP mapping here, for local use.</p>
<p>[1] To run the app locally with a custom domain name (e.g. <code class="language-plaintext highlighter-rouge">mycoolsite.com</code> in our example), add it to the Windows hosts file so that browsers can find it. For that, open any text editor in admin mode, open the file hosts file, and add the custom domain name with localhost IP address i.e. <code class="language-plaintext highlighter-rouge">127.0.0.1</code> on a new line, and save</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># in C:\Windows\System32\drivers\etc\hosts</span>
<span class="s">127.0.0.1 mycoolsite.com</span>
</code></pre></div></div>
<p>[2] To make it available over LAN, add another binding for your website with the IP address of the hosting machine and a port (check <a href="https://stackoverflow.com/questions/21896534/accessing-a-local-website-from-another-computer-inside-the-local-network-in-iis">this</a> post for help). So you’ll actually have two bindings for your site</p>
<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#For Local:</span>
<span class="na">Type</span><span class="pi">:</span> <span class="s">http</span>
<span class="na">Ip Address</span><span class="pi">:</span> <span class="s">All Unassigned</span>
<span class="na">Port</span><span class="pi">:</span> <span class="m">80</span>
<span class="na">Host name</span><span class="pi">:</span> <span class="s">mycoolsite.com</span>
<span class="c1">#For network LAN:</span>
<span class="na">Type</span><span class="pi">:</span> <span class="s">http</span>
<span class="na">Ip Address</span><span class="pi">:</span> <span class="s"><Network address of the hosting machine ex. 190.168.10.50></span>
<span class="na">Port</span><span class="pi">:</span> <span class="s">8080 <make sure this port is allowed to have incoming traffic></span>
<span class="na">Host name</span><span class="pi">:</span> <span class="s"><Leave it blank></span>
</code></pre></div></div>
<p><img src="/images/posts/misc/iis-bindings.png" alt="Image" /></p>
<p>Also, make sure that the port that you used (e.g. 8080) is allowed to receive inbound requests and is not blocked by firewall.</p>A quick guide to deploying your new ASP.NET Core app on existing IIS web serverBasic coding guidelines for OOP2018-08-25T00:00:00+00:002018-08-25T00:00:00+00:00https://arghya.xyz/articles/coding-guidelines<p class="notice--info"><strong>Note:</strong> I wrote this coding specifications for entry/mid level developers of my team, during 2013-14. It was meant to help developers write better code, and also to help peers review code more efficiently. Parts of it might be outdated now, but most of the ideas and practices still apply. Sharing the document as-is.</p>
<hr />
<p>This document describes briefly, the coding standards & practices all the developers (including automation engineers, and anyone who writes code) should follow while developing a software application.</p>
<p>This document is written for any developer <em><strong>working with a modern object oriented programming language</strong></em>. These generic principles and practices apply to almost all modern OOP based programming languages. At few places it uses <code class="language-plaintext highlighter-rouge">C#</code> specific examples, those have been marked specifically.</p>
<p>This document is not exhaustive; it describes only the most important set of guidelines to follow. This document will be updated as and when necessary.</p>
<hr />
<ol>
<li><strong>Readability & Maintainability</strong> – The most important aspects of a long lived codebase.
<ol>
<li>Writing a compiling and running code is inevitable, write code that
<ol>
<li>Others (humans) can read and understand easily</li>
<li>Can be changed or extended with least side effects</li>
</ol>
</li>
<li>Follow <em>“newspaper style”</em> of writing code. Just looking at the structure and names, a fellow developer should understand the overall functionality</li>
<li>Comments – try to avoid. Write code that is self-explanatory
<ol>
<li>But, do write some comments to explain the complex parts, which cannot be understood well enough just by reading. Write xml comments if possible, so that compiler can use that. <code class="language-plaintext highlighter-rouge">C#</code></li>
<li>Keep a <code class="language-plaintext highlighter-rouge">//TODO:</code> task where more work is needed</li>
</ol>
</li>
<li>KISS – keep it short and simple. Do not write long methods or classes. [See DRY section for more on this]</li>
<li>Minimize the scope of everything. [See Scoping for more on this]</li>
<li>Use functional shorthands/Lambda expressions and Linq methods for higher readability. But avoid them if the internal logic is becoming way too complex, and code is losing readability. (Linq is for <code class="language-plaintext highlighter-rouge">C#</code>)</li>
<li>Use ternary operator (condition ? truthy logic : falsy logic) for simple if-else</li>
<li>Cache variables (create local reference) for multiple uses. e.g. define locally and use miltiple times, var lastCustId = _custService. getCustomersByPostcode(postcode). Last(). Profile. AccountDetails. Id; Improves performance and readability, reduces duplication</li>
<li>Remove all kind of redundancy from code [e.g. if (isSuccess == true) return true; else return false; => return isSuccess;].</li>
<li>Don’t litter the whole codebase with business logic in bits and pieces
<ol>
<li>Core business (domain) logic should be within a single module</li>
<li>Do NOT write business login in <code class="language-plaintext highlighter-rouge">JavaScript</code>, except UI validation</li>
<li>Do NOT write UI logic within core application classes (styles, uri, control state etc.)</li>
<li>Application (or behavioural) logic should be confined in specific module (e.g. controllers for MVC applications)</li>
<li>Separate out logic to maintain state (session, cache etc.) from core business logic</li>
</ol>
</li>
</ol>
</li>
<li><strong>Structure</strong> – good code starts with good structure
<ol>
<li>Follow this structure/flow for classes
<ol>
<li>Constants, Read-only fields</li>
<li>Private fields</li>
<li>Properties</li>
<li>Constructor</li>
<li>Public methods, Internal/package-private methods</li>
<li>Protected methods</li>
<li>Private methods</li>
</ol>
</li>
<li>Group code entities logically into Projects/Packages/Modules/Folders
<ol>
<li>Separate logical layers of application into different modules/projects (e.g. Domain, Business logic/Application, UI, data access, services, Infrastructure, Utilities etc.)</li>
<li>Within folders, use sub folder hierarchically to group related/similar entities</li>
</ol>
</li>
<li>Use separate files for each class, struct, interface, enum etc. Name of the file and the enclosing entity must be sam5. (e.g. class Employee in Employee.cs / Employee.java)</li>
</ol>
</li>
<li><strong>Naming</strong> – name that describes the purpose
<ol>
<li>Name of all entities should be meaningful. They should clearly convey the purpose. Project/Package, Namespace, Classes, Interfaces, Properties, Methods, Fields, local variables and even method parameters must follow the convention</li>
<li>Follow proper casing
<ol>
<li>Namespace, Class, Interface, Property, Method, Event, Enumeration Type – must follow <code class="language-plaintext highlighter-rouge">PascalCasing</code></li>
<li>Method parameter, local variables – must follow <code class="language-plaintext highlighter-rouge">camelCasing</code></li>
<li>Test cases, enumeration fields, constants, configuration and resource keys – may contain Underscore_Separator</li>
<li>Use underscored camel case for _privateFields [See scoping section]</li>
<li>Use caps for CONSTANTS or application level variables. Pascal casing can also be used as per platform specific standards [See scoping section]</li>
</ol>
</li>
<li>Start Interface names with ‘I’, followed by a meaningful name in Pascal case</li>
<li>Do NOT use Hungarian naming like strFirstName, intCount, ProductTypeEnum etc.</li>
</ol>
</li>
<li><strong>Scoping</strong> - Minimize scope of everything
<ol>
<li>Define and use everything within the minimum scope possible</li>
<li>Use proper access modifier for all code entities. Use private, protected, internal/package-private, protected-internal (<code class="language-plaintext highlighter-rouge">C#</code>), public - in this precedence</li>
<li>Use naming that visually describes scope like _privateField, CONSTANT etc.</li>
<li>Use readonly/immutable when a field’s value should not be change after initialization</li>
<li>Use only get, for properties that should not be updated from outside</li>
<li>Don’t forget the <em><strong>law of Demeter</strong></em>, entities should have minimum knowledge of outside world [See SOLID section for more on this]</li>
<li>All the code entities (interface, class, package etc.) should have <em><strong>the maximum cohesion and least coupling possible</strong></em>. That means, the members of the entity (e.g. methods in a class) should be very closely related to each other, i.e. cohesion. Also, different entities should have the least inter-dependency as possible, i.e. coupling.</li>
</ol>
</li>
<li><strong>DRY</strong> – it is not an option, DRY is the law
<ol>
<li>Do not repeat code. Think a million times before copy-pasting code</li>
<li>A piece of knowledge (logic, in other word) should exist only in one place within the codebase/application</li>
<li>Reuse code as much as possible
<ol>
<li>If a piece of code can be reused by other components, extract them out into a public method</li>
<li>If a piece of code is executed multiple times within a class, extract it out into a private method. Do it, even if it has just few lines</li>
</ol>
</li>
<li>Always write short methods, short classes</li>
<li>One single method should not have too many logic, long conditional flow or too many parameters (exception can be, for example, mapper methods for third-party/legacy entities)</li>
<li>One single class should not have many methods [See SRP in SOLID]</li>
<li>Methods over 20 lines and classes over 100 lines should be thought through, for possible <strong><em>“separation of concerns”</em></strong>. Separation of concerns is extremely important for a codebase to be maintainable in long term. It basically means, separate your concerns so that different entities (interface, class, package etc.) have their own independent things to take care of. For example, do NOT make the same method read data from database, and also format it for the UI. Reading data and formatting data are two different concerns.</li>
</ol>
</li>
<li><strong>SOLID principles</strong> - follow religiously, they will battle out the evils of bad code
<ol>
<li>Strictly follow <em>Single Responsibility Principle (SRP)</em> when writing methods, classes, modules, projects., packages or any other code entities. They all must have one and only one reason to change</li>
<li>Always follow <em>Open Closed Principle (OCP)</em>. Write classes and other code entities that are easy to extend without modification. Prefer polymorphism over conditional logic, prefer composition over inheritance, use extension methods (<code class="language-plaintext highlighter-rouge">C#</code>) for external or legacy classes, use Visitor and Decorator patterns when applicable</li>
<li>Remember <em>Liskov’s Substitution Principle (LSP)</em> when inheriting. Don’t create sub classes that violate the expected behaviour of base class</li>
<li>Segregate interfaces based on logically related functionalities, follow <em>Interface Segregation Principle (ISP)</em>. In other words, remember SRP when defining abstracts, contracts, APIs</li>
<li>Try to follow <em>Dependency Inversion Principle (DIP)</em> whenever possible (at least when writing new code modules). Code on abstractions not on implementation, implementation should depend on abstraction not the other way round, make high level modules (logic and policy defining modules that are fundamental to the system) independent of low level modules (implementation specific details like UI, database), keep things as loosely coupled as possible. Use IoC containers for binding modules at run time</li>
</ol>
</li>
<li><strong>Tests</strong> – developers miss them way too often!
<ol>
<li>All parts of codebase has to be unit-testable
<ol>
<li>Follow all the coding practices mentioned in this doc</li>
<li>Code on abstraction (read interface), so that they can be mocked and injected</li>
<li>Do not read database, files or call service within non-mockable/static classes</li>
</ol>
</li>
<li>Write test for all the business logic
<ol>
<li>Try to have good coverage. But, more importantly</li>
<li>Do have meaningful set of tests that confirm functional correctness of the application</li>
</ol>
</li>
<li>After any code change, run all the tests and fix them if required (do not alter test such a way that expected behaviour is altered, just to make them pass)</li>
<li>Write related tests before code check-in [see general practices and process section]</li>
</ol>
</li>
<li><strong>Exceptions and logging</strong> – do them properly
<ol>
<li>Always handle exceptions
<ol>
<li>Use <code class="language-plaintext highlighter-rouge">Try-Catch-Finally</code> whenever required</li>
<li>Use exception filter attribute/annotation whenever possible</li>
<li>Do NOT swallow exceptions. Do a <code class="language-plaintext highlighter-rouge">throw;</code> rather than <code class="language-plaintext highlighter-rouge">throw ex;</code></li>
<li>Show proper message in UI as applicable</li>
<li>Do NOT use exception as control flow logic</li>
<li>Do it for <code class="language-plaintext highlighter-rouge">JavaScript</code> code as well, especially when calling a service</li>
</ol>
</li>
<li>Log properly
<ol>
<li>Log exception and other significant event details</li>
<li>Follow the same convention for logging all over the application</li>
</ol>
</li>
</ol>
</li>
<li><strong>Cautions!</strong> – get rid of the bad practices people follow around us
<ol>
<li>Get rid of hard coding
<ol>
<li>Do not use magic strings, magic numbers</li>
<li>If required – use xml/config/resource files for global (configurable) constants</li>
<li>Constants class can be used if the values are not configurable, but use them if absolutely necessary</li>
<li>Define locally used constant values as private constants within the class</li>
</ol>
</li>
<li>Be cautious when using <code class="language-plaintext highlighter-rouge">static</code> keyword
<ol>
<li>Use static methods if they do not use instance (object specific) values</li>
<li>Do NOT use static properties (they can create deep rooted bugs)</li>
</ol>
</li>
<li>Do NOT use partial classes (<code class="language-plaintext highlighter-rouge">C#</code>), unless it is a asp.net web form code behind file</li>
<li>Avoid nested classes</li>
<li>Do NOT randomly use Design Pattern names, which do not represent anything!</li>
</ol>
</li>
<li>General practices and process
<ol>
<li>Always design first, then code. Take time to understand the requirement, discuss with the team, design properly, and then start coding. Do NOT touch the code until the whole thing has been designed at low level</li>
<li>Always get the code reviewed before checking in. NO code check-ins without thorough code. Review -> review comments -> changes per comments. (Or, commit, get reviewed, then push to master, as per team standards). Before committing, always build the project, run the unit tests, run the application and do a quick sanity</li>
<li>Write related tests before code check-in and get them reviewed as well. NO code check-in without related tests</li>
<li>Refactor. It’s a continuous process, do it often (when adding new code, or fixing bugs, or doing general clean up). But do it precisely and methodically, otherwise there is a high chance of breaking existing functionalities. Run tests, to make sure everything is working as expected</li>
<li>Learn and use established Design Patterns, whenever they fit</li>
<li><u>Performance</u> – last but not the least! Always consider <strong>performance and scalability</strong> issues while writing code. [Details of good coding practices for performance & scalability are beyond the scope of this document!]</li>
<li><u>Threading</u> - to increase throughput of application, use multi-threading where applicable. But be very cautious and use standard and understandable constructs only, as incorrect use of them can cause critical bugs in the application which might be very difficult to debug</li>
</ol>
</li>
</ol>
<p><strong>Note 1:</strong> <code class="language-plaintext highlighter-rouge">C#</code> denotes some C# language specific constructs. If you are using some other language for development, similar constructs available for that language/platform can be used.</p>
<p><strong>Note 2:</strong> (2018) Also, it does not consider latest C# features like <code class="language-plaintext highlighter-rouge">dynamic</code>, <code class="language-plaintext highlighter-rouge">async-await</code> and other C# 5.0+ language features.</p>A general coding guidelines for Object Oriented Programming, like C# and othersWhat is GraphQL & how to use it2018-07-07T00:00:00+00:002018-07-07T00:00:00+00:00https://arghya.xyz/articles/what-is-graphql<h1 id="graphql">GraphQL</h1>
<p>The term <code class="language-plaintext highlighter-rouge">GraphQL</code> has been around for quite a while, but still it is not very clear to many developers what it really is! At least it wasn’t for me. Also, many people relate GraphQL and Graph Databases, which are actually not related in any way! Some of the definitions on the internet can also be confusing! So let’s just try simplify the terminology & wrap our head around the basic concepts, and see if it can help us solve some of our real life problems.</p>
<h4 id="what-is-graphql">What is GraphQL</h4>
<p><u>GraphQL is an API standard</u>. It defines a way of building smart APIs where the client can ask for exactly what data is needed, and the API server returns the same data as requested by the client.</p>
<blockquote>
<p>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. - <a href="http://graphql.github.io/">GraphQL home</a></p>
</blockquote>
<p>GraphQL stands for “Graph Query Language”. It’s not a database query language like SQL, it is a way of building standard APIs like REST principles, which allows data queries. It can also be thought of as a smart way of fetching data.</p>
<p><a href="https://graphql.org/">GraphQL</a> was initially designed in Facebook for their back-end services for web & mobile clients. It was made <a href="https://github.com/graphql">open source</a> in 2015 and now it’s supported by a large community.</p>
<p>Since it’s more of a standard than a specific implementation, it’s possible to use them on almost any platform. There is already support in many languages for <a href="http://graphql.github.io/code/">GraphQL servers</a> & <a href="http://graphql.github.io/code/#graphql-clients">clients</a> including <code class="language-plaintext highlighter-rouge">JavaScript</code>, <code class="language-plaintext highlighter-rouge">Java</code>, <code class="language-plaintext highlighter-rouge">C#/.NET</code>, <code class="language-plaintext highlighter-rouge">Go</code>, <code class="language-plaintext highlighter-rouge">Python</code>, <code class="language-plaintext highlighter-rouge">Scala</code> etc.</p>
<h4 id="why--how">Why & How</h4>
<p>GraphQL was initially developed to overcome some of the limitations of the standard REST APIs. We all know REST APIs are great and they power most of the small-large applications today. But, it has its own limitations.</p>
<p>The REST endpoints are generally like this</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/users <span class="c">#Get all users</span>
/users/id <span class="c">#Get a specific user</span>
/users/id/email <span class="c">#Get an user's email</span>
/users/id/skills <span class="c">#Get an user's skills</span>
</code></pre></div></div>
<p>The main problems with this are</p>
<ol>
<li>When we ask for user data, we get all the info (name, email, dob, sex, department, accounts etc.) about the user. But we might need just a few pieces of the info (e.g. name & email), rest are redundant for the client. This unnecessary data increases the payload, eats up more memory to process and slows down the network calls.</li>
<li>If you want multiple pieces of small info e.g. email & skills (maybe you are a recruiter), you have to make multiple calls. Adds performance overhead and complexity.</li>
<li>As more and more data are made available through the APIs, the developers have to keep adding and maintaining more and more APIs.</li>
</ol>
<p><em>GraphQL</em> aims to solve these problems.</p>
<p>GraphQL lets the client define exactly what data it is looking for, and GraphQL servers are capable of parsing the query and serving exactly what is requested. Let’s take an example</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//Client asks for</span>
<span class="nx">query</span> <span class="p">{</span>
<span class="nx">user</span> <span class="p">(</span><span class="nx">id</span><span class="p">:</span> <span class="mi">1291</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">email</span><span class="p">,</span>
<span class="nx">skills</span><span class="p">,</span>
<span class="nx">knowsHtml</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c1">//Server returns</span>
<span class="p">{</span>
<span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span>
<span class="dl">"</span><span class="s2">user</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span>
<span class="dl">"</span><span class="s2">email</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">cooldeveloper@email.com</span><span class="dl">"</span><span class="p">,</span>
<span class="dl">"</span><span class="s2">skills</span><span class="dl">"</span><span class="p">:</span> <span class="p">[</span> <span class="dl">"</span><span class="s2">Golang</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">Scala</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">REST</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">GraphQL</span><span class="dl">"</span> <span class="p">],</span>
<span class="dl">"</span><span class="s2">knowsHtml</span><span class="dl">"</span><span class="p">:</span> <span class="kc">true</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p class="notice--info"><strong>Note:</strong> With GraphQL you can build a <em><strong>smart API with just one endpoint</strong></em>. On the same endpoint, client can request any data that it wants, and the server responds with that exact data in the same requested format.</p>
<p>The name <em>“GraphQL”</em> came from the idea, that it lets you <em>“query”</em> (QL = Query Language) through the nested structure of data, which is like a <em>“graph”</em>. Generally, it also supports <em>mutation</em> or data update.</p>
<h4 id="how-does-it-work">How does it work</h4>
<p>GraphQL works based on 3 main components</p>
<ol>
<li>Type / Schema</li>
<li>Query</li>
<li>Resolver</li>
</ol>
<p>Since the client can query the data model, it’s required to have a clear definition of the data model. GraphQL servers define the structure of data through <strong><code class="language-plaintext highlighter-rouge">types or schema</code></strong>. Different languages can define the schema in their own way, but on a high level they all basically specify what fields are available and what are their types. Without being specific to a language, let’s see what the type definition looks like in general. For more details, see the documentation <a href="https://graphql.org/learn/schema/">here</a>.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">type</span> <span class="nx">User</span> <span class="p">{</span>
<span class="nl">id</span><span class="p">:</span> <span class="nx">ID</span><span class="p">,</span>
<span class="nx">name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">email</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">dob</span><span class="p">:</span> <span class="nb">Date</span><span class="p">,</span>
<span class="nx">skills</span><span class="p">:</span> <span class="p">[</span><span class="nb">String</span><span class="p">],</span>
<span class="nx">address</span><span class="p">:</span> <span class="nx">Address</span>
<span class="p">}</span>
<span class="nx">type</span> <span class="nx">Address</span> <span class="p">{</span>
<span class="nl">streetLine1</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">streetLine2</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">city</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">state</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">zip</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
<span class="nx">country</span><span class="p">:</span> <span class="nb">String</span>
<span class="p">}</span>
</code></pre></div></div>
<p>With the type or schema defined by the server, the client knows what all data it can query for. Now, based on need, client can <strong><code class="language-plaintext highlighter-rouge">query</code></strong> for the exact the data it needs.</p>
<p>In the query, the required fields/properties of data are listed. For nested types, the fields of the child types also need to be defined. For the root object, or nested types or arrays, parameters can also be passed to narrow down specific data (e.g. id:1234 to ask for data related to item with id=1234), define format etc.</p>
<p>GitHub provides a nice interface to write interactive GraphQL queries on its live, public data. Check it out <a href="https://developer.github.com/v4/explorer/">here</a> and do try out some queries.</p>
<p><img src="/images/posts/misc/github-graphiql.png" alt="Image" /></p>
<p>Now, on the API side, the server needs to know how to fulfil the queries. To do this, the GraphQL servers use some specialized <em><code class="language-plaintext highlighter-rouge">GraphQL execution engine</code></em> that knows <em>how to get data for each fields defined in the schema</em> and combine them into requested form.</p>
<p>So when the server receives the query, it parses and executes the query. If something is found wrong (e.g. a field that is not defined in the schema), it throws a user-friendly message stating what went wrong with the query.</p>
<p>Generally it produces a bunch of smaller queries to fulfil individual fields requested in the query. Then the execution engine tries to run all the queries in most efficient manner, concurrently and combines them back to produce the final result. This result is sent back to the client in the original requested format, generally as <code class="language-plaintext highlighter-rouge">JSON</code>.</p>
<p class="notice--info"><strong>Note:</strong> There is no constraint on the source of data. For example, it’s totally fine to get some audit records from a SQL Server database, user document from MongoDB and transaction details from another API.</p>
<p>The actual implementation of the resolver is technology specific. But again, without going into a specific technology or language, a <strong><code class="language-plaintext highlighter-rouge">resolver</code></strong> is a function for each field in the schema, that defines how to fetch the data for that field. Each field resolver function can fetch the data directly from a database, or from the data already fetched for the parent type, or get it from filesystem or another API or any possible source.</p>
<p>A typical code for a type resolver would look something like this</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">User</span> <span class="nf">ResolveUser</span><span class="p">(</span><span class="kt">int</span> <span class="n">id</span><span class="p">)</span> <span class="p">{</span>
<span class="kt">var</span> <span class="n">user</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="n">Get</span><span class="p"><</span><span class="n">User</span><span class="p">>(</span><span class="n">u</span> <span class="p">=></span> <span class="n">u</span><span class="p">.</span><span class="n">id</span> <span class="p">==</span> <span class="n">id</span><span class="p">);</span> <span class="c1">//the type</span>
<span class="n">user</span><span class="p">.</span><span class="nf">AddField</span><span class="p">(</span><span class="n">u</span> <span class="p">=></span> <span class="n">u</span><span class="p">.</span><span class="n">Id</span><span class="p">);</span> <span class="c1">//standard field resolvers</span>
<span class="n">user</span><span class="p">.</span><span class="nf">AddField</span><span class="p">(</span><span class="n">u</span> <span class="p">=></span> <span class="n">u</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
<span class="n">user</span><span class="p">.</span><span class="nf">AddField</span><span class="p">(</span><span class="n">u</span> <span class="p">=></span> <span class="n">u</span><span class="p">.</span><span class="n">Email</span><span class="p">);</span>
<span class="n">user</span><span class="p">.</span><span class="nf">AddField</span><span class="p">(</span><span class="s">"totalUsers"</span><span class="p">,</span> <span class="p">(</span><span class="n">db</span><span class="p">,</span> <span class="n">u</span><span class="p">)</span> <span class="p">=></span> <span class="n">db</span><span class="p">.</span><span class="n">Users</span><span class="p">.</span><span class="nf">Count</span><span class="p">());</span> <span class="c1">//custom resolvers</span>
<span class="n">user</span><span class="p">.</span><span class="nf">AddField</span><span class="p">(</span><span class="s">"skills"</span><span class="p">,</span> <span class="p">(</span><span class="n">db</span><span class="p">,</span> <span class="n">u</span><span class="p">)</span> <span class="p">=></span> <span class="n">u</span><span class="p">.</span><span class="n">Skills</span><span class="p">.</span><span class="nf">Select</span><span class="p">(</span><span class="n">s</span> <span class="p">=></span> <span class="n">s</span><span class="p">.</span><span class="n">Name</span><span class="p">).</span><span class="nf">ToArray</span><span class="p">());</span>
<span class="k">return</span> <span class="n">user</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<h4 id="some-common-questions">Some common questions</h4>
<ol>
<li><em>Is GraphQL related to Graph Databases?</em> No. Not at all. GraphQL is an API standard, much like REST. It has nothing to do with any specific database technology. a GraphQL server can be implemented with any backing database given a proper resolver is in place, which can translate GraphQL queries to results.</li>
<li><em>Does that mean all REST services will be replaced with GraphQL APIs?</em> No. REST, SOAP, GraphQL and everything else has its pros and cons. For many applications, the current REST APIs are sufficient, and there is no need to change anything. Specific applications that need lot of flexibility and clients are smart enough to query specific data, those can benefit from GraphQL.</li>
<li><em>What technology is required to use GraphQL?</em> Since GraphQL is a standard and not an implementation, there is no technology constraint as such. Virtually any tech-stack or programming language can be used. But it’s better to use it with one of the <a href="http://graphql.github.io/code/">existing GraphQL solutions</a> which are well tested and supported.</li>
</ol>
<h4 id="references">References</h4>
<ul>
<li><a href="http://graphql.github.io/">The GraphQL homepage</a></li>
<li><a href="https://github.com/graphql">GitHub repos</a></li>
<li><a href="http://graphql.github.io/learn/">Official docs</a></li>
<li><a href="https://facebook.github.io/graphql/#sec-Language">GraphQL specifications</a></li>
<li><a href="https://www.howtographql.com/">How to GraphQL - tutorials</a></li>
<li><a href="https://medium.freecodecamp.org/so-whats-this-graphql-thing-i-keep-hearing-about-baf4d36c20cf">A great intro to GraphQL</a></li>
</ul>A very basic introduction to GraphQL. Do you query graph database with it?Non-blocking multithreading & concurrent collections | Thread synchronization Part IV2018-06-09T00:00:00+00:002018-06-09T00:00:00+00:00https://arghya.xyz/articles/thread-synchronization-part-four<p>In this post, we’ll look at some non-blocking constructs provided by the .NET framework for safer access of data in multithreading environments. We’ll also look at some potential issues in multithreading and the thread-safe concurrent collections. This is the last post in the multithreading series, following <strong><a href="/articles/thread-synchronization-part-three/">Multithreading with signals | Thread synchronization Part III</a></strong>.</p>
<h2 id="non-blocking-constructs">Non-blocking constructs</h2>
<p>.NET Framework provides a bunch of non-blocking synchronization constructs can perform simple operations without ever blocking, pausing, or waiting threads. They also work across multiple processes.</p>
<p>The <strong><code class="language-plaintext highlighter-rouge">MemoryBarrier</code></strong></p>
<blockquote>
<p>Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier. - from <a href="https://msdn.microsoft.com/en-us/library/system.threading.thread.memorybarrier.aspx">MSDN</a></p>
</blockquote>
<p>In <em>slightly</em> simpler terms, it prevents any kind of instruction reordering or caching around that fence due to compiler optimization. So, it works as a wall or barrier preventing instructions or memory access going across it.</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//vague, not a real example</span>
<span class="n">Thread</span><span class="p">.</span><span class="nf">MemoryBarrier</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">_jobCompleted</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">Thread</span><span class="p">.</span><span class="nf">MemoryBarrier</span><span class="p">();</span>
<span class="n">log</span> <span class="p">=</span> <span class="s">$"Result = </span><span class="p">{</span><span class="n">_resultFromJob</span><span class="p">}</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p class="notice--danger"><strong>Note:</strong> The use of <code class="language-plaintext highlighter-rouge">MemoryBarrier</code> may lead to complicated, hard to debug pitfalls. Same can happen with <code class="language-plaintext highlighter-rouge">volatile</code>, <code class="language-plaintext highlighter-rouge">VolatileRead</code> and <code class="language-plaintext highlighter-rouge">VolatileWrite</code> explained below. Read it from Albahari’s <a href="http://www.albahari.com/threading/part4.aspx#_Memory_Barriers_and_Volatility">book</a> for detailed explanation and examples. Simply putting a <strong><code class="language-plaintext highlighter-rouge">lock()</code></strong> around those field access is generally much more safe and error free, at a potential cost of a very minor performance loss (in order of 10s of nano seconds).</p>
<p>The <code class="language-plaintext highlighter-rouge">volatile</code> declaration on a field, and the <code class="language-plaintext highlighter-rouge">volatileRead</code> & <code class="language-plaintext highlighter-rouge">VolatileWrite</code> static methods on <code class="language-plaintext highlighter-rouge">Thread</code> class basically tries to ensure that all threads get latest values available, when multiple threads (and OS, hardware etc.) are accessing them simultaneously.</p>
<p><strong><code class="language-plaintext highlighter-rouge">Thread.VolatileRead</code></strong> & <strong><code class="language-plaintext highlighter-rouge">Thread.VolatileWrite</code></strong> makes sure all processor/threads get the latest value (read), or currently written value (write) is immediately available to all.</p>
<blockquote>
<p>VolatileRead and VolatileWrite are for special cases of synchronization. Under normal circumstances, the C# lock statement, the Visual Basic SyncLock statement, and the Monitor class provide easier alternatives. - <a href="https://msdn.microsoft.com/en-us/library/bah54t54(v=vs.110).aspx">MSDN</a></p>
</blockquote>
<p>The <strong><code class="language-plaintext highlighter-rouge">volatile</code></strong> keyword, when used against reference and some other allowed types (enum , pointer, byte, int etc.), JIT prevents any code optimization around it and prevents threads from caching its value. The main intention is to <em>always get the latest value</em> of the variable in scenarios where other threads or the OS itself might be updating the value. More details <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile">here</a>.</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//all threads/processors will always get latest value of this</span>
<span class="k">public</span> <span class="k">volatile</span> <span class="kt">int</span> <span class="n">_criticalCount1</span> <span class="p">=</span> <span class="m">1</span><span class="p">;</span>
<span class="k">private</span> <span class="kt">int</span> <span class="n">_criticalCount2</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
<span class="k">public</span> <span class="kt">int</span> <span class="nf">UpdateAndRead</span><span class="p">(</span><span class="kt">int</span> <span class="k">value</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">//write and make new value available to all threads/processors</span>
<span class="n">Thread</span><span class="p">.</span><span class="nf">VolatileWrite</span><span class="p">(</span><span class="k">ref</span> <span class="n">_criticalCount2</span><span class="p">,</span> <span class="k">value</span><span class="p">);</span>
<span class="c1">//read latest value, in case some thread/processor has updated it</span>
<span class="kt">int</span> <span class="n">updatedVal</span> <span class="p">=</span> <span class="n">Thread</span><span class="p">.</span><span class="nf">VolatileRead</span><span class="p">(</span><span class="k">ref</span> <span class="n">_criticalCount2</span><span class="p">);</span>
<span class="k">return</span> <span class="n">updatedVal</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p><strong>In general, it is advisable to use <code class="language-plaintext highlighter-rouge">lock</code> and avoid these low-level memory constructs in normal circumstances.</strong> One needs to understand them at a very low level, and the platform’s memory model at large, to apply them in a correct and benefiting way. For some detailed discussion, check <a href="https://blogs.msdn.microsoft.com/ericlippert/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/">Eric Lippert’s posts</a>.</p>
<h2 id="interlocked">Interlocked</h2>
<p>The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked?view=netframework-4.7.2">Interlocked</a> class provides <em>atomic</em> (as one single unit of work, in a single step) operations on <em>variables</em> that may be accesses by multiple threads. Even simple operations like updating/incrementing a value, or adding two values are not a single-step operation in most platforms. This <em>may</em> cause issues if a thread is time-sliced in-between the process and other thread is trying to access the same variable. Interlocked can prevent those scenarios, by making the work atomic to the OS.</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//update a value atomically</span>
<span class="kt">int</span> <span class="n">sharedVar</span> <span class="p">=</span> <span class="m">1</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">original</span> <span class="p">=</span> <span class="n">Interlocked</span><span class="p">.</span><span class="nf">Exchange</span><span class="p">(</span><span class="k">ref</span> <span class="n">sharedVar</span><span class="p">,</span> <span class="m">2</span><span class="p">);</span>
<span class="c1">//add 2 numbers atomically</span>
<span class="kt">int</span> <span class="n">a</span> <span class="p">=</span> <span class="m">5</span><span class="p">,</span> <span class="n">b</span> <span class="p">=</span> <span class="m">10</span><span class="p">;</span> <span class="c1">//a gets the sum value</span>
<span class="kt">int</span> <span class="n">sum</span> <span class="p">=</span> <span class="n">Interlocked</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">ref</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">);</span>
</code></pre></div></div>
<p>Typical scenario where <code class="language-plaintext highlighter-rouge">Interlocked</code> would be helpful is, when a method in a class modifies a <code class="language-plaintext highlighter-rouge">static</code> variable (e.g. a class-level private field, NOT a variable local to the method), and the method may run on multiple threads concurrently!</p>
<p class="notice--info"><strong>Note:</strong> A simple read or write on a field of 32 bits or less is always atomic. Operations on 64-bit fields are guaranteed to be atomic only in a 64-bit runtime environment, and statements that combine more than one read/write operation are never atomic. For example, writing to a <code class="language-plaintext highlighter-rouge">long</code> is not atomic on 32 bit machine, and <code class="language-plaintext highlighter-rouge">i++</code> where <code class="language-plaintext highlighter-rouge">i</code> is <code class="language-plaintext highlighter-rouge">Int32</code> is still not atomic. - from <a href="http://www.albahari.com/threading/part4.aspx">Albahari</a></p>
<h2 id="some-common-issues-with-multi-threading">Some common issues with multi-threading</h2>
<p><strong>Thread safety</strong>: A piece of code or data structure is thread safe, when the outcome of the code and underlying resources do not create undesirable results (inconsistent data, exception etc.) as a result of multiple threads interacting with the code concurrently.</p>
<p><strong>Thread contention</strong>: When a thread has to wait to do some work or use a resource, because that is not readily available (e.g. locked by another thread or other reasons), and slows down because of that.</p>
<p><strong>Race condition</strong>: In most general form, when two or more threads are trying to update a shared data at the same time. Based on OS scheduling and time-slicing, the threads may update the value in any order (like a race event). Because of that, the final state of data is unpredictable and the program can produce unexpected results.</p>
<p><strong>Deadlock</strong>: When two or more threads are holding locks (on a <em>“critical section”</em> of code or a resource) and waiting for the other thread(s) to release their resource (so that it can lock/use that), they come to a stand still waiting on each-other. This undesirable situation is known as a deadlock!</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="k">readonly</span> <span class="kt">object</span> <span class="n">locker1</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">object</span><span class="p">();</span>
<span class="k">static</span> <span class="k">readonly</span> <span class="kt">object</span> <span class="n">locker2</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">object</span><span class="p">();</span>
<span class="k">new</span> <span class="nf">Thread</span><span class="p">(()</span> <span class="p">=></span> <span class="p">{</span> <span class="c1">//worker thread</span>
<span class="k">lock</span> <span class="p">(</span><span class="n">locker1</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">Thread</span><span class="p">.</span><span class="nf">Sleep</span><span class="p">(</span><span class="m">1000</span><span class="p">);</span>
<span class="k">lock</span> <span class="p">(</span><span class="n">locker2</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">// Deadlock</span>
<span class="p">}</span>
<span class="p">}).</span><span class="nf">Start</span><span class="p">();</span>
<span class="k">lock</span> <span class="p">(</span><span class="n">locker2</span><span class="p">)</span> <span class="c1">//main thread</span>
<span class="p">{</span>
<span class="n">Thread</span><span class="p">.</span><span class="nf">Sleep</span><span class="p">(</span><span class="m">1000</span><span class="p">);</span>
<span class="k">lock</span> <span class="p">(</span><span class="n">locker1</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">// Deadlock</span>
<span class="p">}</span>
</code></pre></div></div>
<p>So, what kind of code is at risk of above type of issues? Any code that works on shared resources or data structures, that might be accessed by multiple threads concurrently, are at risk. Most common example would be <code class="language-plaintext highlighter-rouge">static</code> methods, properties or class level fields. Remember that the static methods that are part of .NET framework libraries, are made thread safe. But for user code, it’s the programmers’ responsibility to make them <em>thread safe</em>.</p>
<h2 id="thread-safe-or-concurrent-collections">Thread safe or concurrent collections</h2>
<p>.NET Framework 4.0 introduced a new bunch of collections under the namespace <a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent?view=netframework-4.7.2">System.Collections.Concurrent</a>, that are thread-safe by nature. That means, they can be read or be written safely even when multiple threads are accessing them concurrently.</p>
<p>The <a href="https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/">thread-safe collections</a> use lightweight synchronization mechanisms such as <code class="language-plaintext highlighter-rouge">SpinLock</code>, <code class="language-plaintext highlighter-rouge">SpinWait</code>, <code class="language-plaintext highlighter-rouge">SemaphoreSlim</code>, and <code class="language-plaintext highlighter-rouge">CountdownEvent</code> making them very efficient under multithreading environment. The <code class="language-plaintext highlighter-rouge">ConcurrentQueue<T></code> and <code class="language-plaintext highlighter-rouge">ConcurrentStack<T></code> classes do not use locks at all. Instead, they rely on <code class="language-plaintext highlighter-rouge">Interlocked</code> operations to achieve thread-safety.</p>
<p>Some of the very useful thread-safe collections are (there are more)</p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentbag-1?view=netframework-4.7.2">ConcurrentBag<T></a> : thread-safe collection of unordered items</li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1?view=netframework-4.7.2">ConcurrentQueue<T></a> : thread-safe FIFO collection</li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentstack-1?view=netframework-4.7.2">ConcurrentStack<T></a> : thread-safe LIFO collection</li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=netframework-4.7.2">ConcurrentDictionary<TKey,TValue></a> : thread-safe collection of key-value pairs</li>
</ul>
<p>They all provide safe methods for adding data, and useful properties like <code class="language-plaintext highlighter-rouge">IsEmpty</code> and <code class="language-plaintext highlighter-rouge">Count</code>. The <code class="language-plaintext highlighter-rouge">ConcurrentDictionary</code> provides an additional bunch of practical methods like <code class="language-plaintext highlighter-rouge">AddOrUpdate()</code>, <code class="language-plaintext highlighter-rouge">GetOrAdd()</code> etc.</p>
<p>The code below, shows simple demo of <code class="language-plaintext highlighter-rouge">ConcurrentBag</code> and <code class="language-plaintext highlighter-rouge">ConcurrentStack</code>.</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="k">void</span> <span class="nf">ConcurrentBagDemo</span><span class="p">()</span>
<span class="p">{</span>
<span class="c1">//instantiate with values from IEnumerable<T></span>
<span class="kt">var</span> <span class="n">safeBag</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ConcurrentBag</span><span class="p"><</span><span class="kt">string</span><span class="p">>(</span><span class="k">new</span> <span class="kt">string</span><span class="p">[]</span> <span class="p">{</span> <span class="s">"a"</span><span class="p">,</span> <span class="s">"b"</span><span class="p">,</span> <span class="s">"c"</span> <span class="p">});</span>
<span class="kt">bool</span> <span class="n">isBagEmpty</span> <span class="p">=</span> <span class="n">safeBag</span><span class="p">.</span><span class="n">IsEmpty</span><span class="p">;</span> <span class="c1">//false</span>
<span class="kt">int</span> <span class="n">itemsInBag</span> <span class="p">=</span> <span class="n">safeBag</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span> <span class="c1">//3</span>
<span class="n">safeBag</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"another item"</span><span class="p">);</span> <span class="c1">//add an item to bag</span>
<span class="c1">//this will get items in any order</span>
<span class="k">while</span> <span class="p">(</span><span class="n">safeBag</span><span class="p">.</span><span class="nf">TryTake</span><span class="p">(</span><span class="k">out</span> <span class="kt">string</span> <span class="n">result</span><span class="p">))</span> <span class="c1">//C# 7.0 construct</span>
<span class="p">{</span>
<span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"Got item </span><span class="p">{</span><span class="n">result</span><span class="p">}</span><span class="s">"</span><span class="p">);</span> <span class="c1">//will iterate 4 times</span>
<span class="p">}</span>
<span class="c1">//now that bag is empty, TryTake will return FALSE</span>
<span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"More items in bag? </span><span class="p">{</span><span class="n">safeBag</span><span class="p">.</span><span class="nf">TryTake</span><span class="p">(</span><span class="k">out</span> <span class="kt">string</span> <span class="n">item</span><span class="p">)}</span><span class="s">"</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">static</span> <span class="k">void</span> <span class="nf">ConcurrentStackDemo</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">safeStack</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ConcurrentStack</span><span class="p"><</span><span class="kt">string</span><span class="p">>();</span>
<span class="c1">//add strings "1" - "5" to stack</span>
<span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">item</span> <span class="k">in</span> <span class="n">Enumerable</span><span class="p">.</span><span class="nf">Range</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">5</span><span class="p">))</span>
<span class="p">{</span>
<span class="n">safeStack</span><span class="p">.</span><span class="nf">Push</span><span class="p">(</span><span class="n">item</span><span class="p">.</span><span class="nf">ToString</span><span class="p">());</span>
<span class="p">}</span>
<span class="kt">bool</span> <span class="n">isStackEmpty</span> <span class="p">=</span> <span class="n">safeStack</span><span class="p">.</span><span class="n">IsEmpty</span><span class="p">;</span> <span class="c1">//false</span>
<span class="kt">int</span> <span class="n">itemsInStack</span> <span class="p">=</span> <span class="n">safeStack</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span> <span class="c1">//5</span>
<span class="c1">//add multiple items with PushRange()</span>
<span class="n">safeStack</span><span class="p">.</span><span class="nf">PushRange</span><span class="p">(</span><span class="k">new</span> <span class="kt">string</span><span class="p">[]</span> <span class="p">{</span> <span class="s">"x"</span><span class="p">,</span> <span class="s">"y"</span><span class="p">,</span> <span class="s">"z"</span> <span class="p">});</span>
<span class="kt">var</span> <span class="n">data</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">string</span><span class="p">[</span><span class="m">2</span><span class="p">];</span> <span class="c1">//try pop 2 items at a time, into data</span>
<span class="k">while</span> <span class="p">(</span><span class="n">safeStack</span><span class="p">.</span><span class="nf">TryPopRange</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="p">></span> <span class="m">0</span><span class="p">)</span> <span class="c1">//no. of items popped</span>
<span class="p">{</span>
<span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"Got items </span><span class="p">{</span><span class="n">String</span><span class="p">.</span><span class="nf">Join</span><span class="p">(</span><span class="sc">','</span><span class="p">,</span> <span class="n">data</span><span class="p">)}</span><span class="s">"</span><span class="p">);</span>
<span class="n">data</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">string</span><span class="p">[</span><span class="m">2</span><span class="p">];</span> <span class="c1">//no old data in case of partial read</span>
<span class="p">}</span> <span class="c1">//this loop will iterate 4 times, 4 * 2 = 8</span>
<span class="p">}</span>
</code></pre></div></div>
<h6 id="all-posts-in-the-series---tasks-threads-asynchronous">All posts in the series - Tasks, Threads, Asynchronous</h6>
<ul>
<li><strong><a href="/articles/sync-to-async-in-dotnet/">Synchronous to asynchronous in .NET</a></strong></li>
<li><strong><a href="/articles/task-cancellation/">Basic task cancellation demo in C#</a></strong></li>
<li><strong><a href="/articles/async-await/">How does Async-Await work - Part I</a></strong></li>
<li><strong><a href="/articles/async-await-2/">How does Async-Await work - Part II</a></strong></li>
<li><strong><a href="/articles/thread-synchronization-part-one/">Multithreading - lock, Monitor & Mutex | Thread synchronization Part I</a></strong></li>
<li><strong><a href="/articles/thread-synchronization-part-two/">Multithreading with non-exclusive locks | Thread synchronization Part II</a></strong></li>
<li><strong><a href="/articles/thread-synchronization-part-three/">Multithreading with signals | Thread synchronization Part III</a></strong></li>
<li><strong>Non-blocking multithreading & concurrent collections | Thread synchronization Part IV</strong></li>
</ul>Non-blocking thread synchronization, multithreading issues and concurrent collections in .NET