npm-run-script

Run arbitrary package scripts

Synopsis

npm run-script <command> [-- <args>...]

alias: npm run

Description

This runs an arbitrary command from a package’s “scripts” object. If no “command” is provided, it will list the available scripts. run[-script] is used by the test, start, restart, and stop commands, but can be called directly, as well. When the scripts in the package are printed out, they’re separated into lifecycle (test, start, restart) and directly-run scripts.

As of npm@2.0.0, you can use custom arguments when executing scripts. The special option — is used by getopt to delimit the end of the options. npm will pass all the arguments after the — directly to your script:

npm run test -- --grep="pattern"

The arguments will only be passed to the script specified after npm run and not to any pre or post script.

The env script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. If an “env” command is defined in your package it will take precedence over the built-in.

In addition to the shell’s pre-existing PATH, npm run adds node_modules/.bin to the PATH provided to scripts. Any binaries provided by locally-installed dependencies can be used without the node_modules/.bin prefix. For example, if there is a devDependency on tap in your package, you should write:

"scripts": {"test": "tap test/\*.js"}

instead of "scripts": {"test": "node_modules/.bin/tap test/\*.js"} to run your tests.

If you try to run a script without having a node_modules directory and it fails, you will be given a warning to run npm install, just in case you’ve forgotten.

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package’s “start” property of its “scripts” object. If no “start” property is specified on the “scripts” object, it will run node server.js.

As of npm@2.0.0, you can use custom arguments when executing scripts. Refer to npm-run-script for more details.

Note for Angular.io (Angular)

Architecture overview

The basic building blocks of Angular 2 applications

Modules

Angular has its modularity system called Angular modules or NgModules.

Every Angular app has at least one module, the root module, conventionally named AppModule.

maybe root module be the only module in the small application, or many more feature modules in most apps.

Angular module is a class with an @NgModule decorator.

NgModule properties
|—->declarations: [‘view classes, eg. components, directives and pipes’].
|—->exports: the subset of declarations that should be visible and usable in the component templates of the modules.
|—->imports: other modules whose exported classes are needed by component templates declared in this module.
|—->providers: services
|—->bootstrap: the main application view, called the root component, that hosts all other app views.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [ BrowserModule ],
providers: [ Logger ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Launch an application by bootstrapping its root module. During development you’re likely to bootstrap the AppModule in a main.ts file like this one.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Angular libraries

Angular ships as a collection of JavaScript modules. You can think of them as library modules.

Each Angular library name begins with the @angular prefix.

You install them with the npm package manager and import parts of them with JavaScript import statements.

Components

A component controls a patch of screen called a view.

You define a component’s application logic - what it does to support the view - inside a class.

The class interacts with the view through an API of properties and methods.

export class HeroListComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;

constructor(private service: HeroService) { }

ngOnInit() {
this.heroes = this.service.getHeroes();
}

selectHero(hero: Hero) { this.selectedHero = hero; }
}

Templates

You define a component’s view with its companion template.

<h2>Hero List</h2>
<p><i>Pick a hero from the list</i></p>
<ul>
<li *ngFor="let hero of heroes" (click)="selectHero(hero)">
{{hero.name}}
</li>
</ul>
<hero-detail *ngIf="selectedHero" [hero]="selectedHero"></hero-detail>

Metadata

Metadata tells Angular how to process a class.

Attaching metadata to the class to tell Angular that a class is a component.

In TypeScript, you attach metadata by using a decorator.

@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
providers: [ HeroService ]
})
export class HeroListComponent implements OnInit {
/* . . . */
}

@Component properties:
|—->selector: CSS selector.
|—->templateUrl: address of this component’s HTML template.
|—->directives: array of the components or directives that this template requires.
|—->providers: array of dependency injection providersfor the services that the component requires.

Data binding

Angular supports data binding,

databinding

4 forms of data binding syntax.

<li>{{hero.name}}</li>
<hero-detail [hero]="selectedHero"></hero-detail>
<li (click)="selectHero(hero)"></li>
  • The interpolation display the component’s hero.name property value within the <li> tags.
  • The [hero] property binding passes the value of selectedHero from the parent HeroListComponent to the hero property of the child HeroDetailComponent.
  • The (click) event binding calls the component’s selelctHero method when the user clicks a hero’s name.
<input [(ngModel)]="hero.name">
  • Two-way data binding
    Combines property and event binding in a single notation, using the ngModel.

Angular processes all data bindings once per JavaScript event cycle, from the root of the application component tree through all child components.

component-databinding

parent-child-binding

Directives

Angular templates are dynamic.
When Angular renders them, it transforms the DOM according to the instructions given by directives.

@Directive

A component is a directive-with-a-template;
A @Component decorator is actually a @Directive decorator extended with template-oriented features.

While a component is technically a directive, components are so distinctive and central to Angular applications that
this architectual overview separates components from directives.

structural directive attribute directive

Structural directives alter layout by adding, removing, and replacing elements in DOM.

<li *ngFor="let hero of heroes"></li>
<hero-detail *ngIf="selectedHero"></hero-detail>

Attribute directives alter the appearance or behavior of an existing element.
In templates they look like regular HTML attributes, hence the name.

E.g. ngModel
ngModel modifies the behavior of an existing element (typically an <input> tag) by setting its display value property and responding to change events.

<input [(ngModel)]="hero.name">

Angular has a few more directives that either alter the layout structure (for example, ngSwitch) or modify aspects of DOM elements and components (for example, ngStyle and ngClass).

Then create your own directives.

Services

Service is a broad category encompassing any value, function, or feature that your application needs.

A service is typically a class with a narrow, well-defined purpose.

export class Logger {
log(msg: any) { console.log(msg); }
error(msg: any) { console.error(msg); }
warn(msg: any) { console.warn(msg); }
}
export class HeroService {
private heros: Hero[] = [];

constructor(
private backend: BackendService,
private logger: Logger
) {}


getHeroes() {
this.backend.getAll(Hero).then((heroes: Hero[]) => {
this.logger.log(`Fetched ${heroes.length} heroes.`);
this.heroes.push(...heroes); // fill cache
});

return this.heroes;
}
}

Dependency Injection

Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires.
Most dependencies are services.
Angular uses dependency injection to provide new components with the services they need.

constructor(private service: HeroService) {}

When Angular creates a component, it first asks an injector for the services that the component requires.

An injector maintains a container of service instances that it has previously created.
if a requested service instance is not in the container, the injector makes one and adds it to the container before returning the service to angular.
When all requested services have been resolved and returned, Angular can call the component’s constructor with those services as arguments.
This is dependency injection.

If the injector doesn’t have a HeroService, how does it know how to make one ?

In brief, you must have previously registered a provider of the HeroService with the injector.

  • Register providers in modules.

Add providers to the root module so that the same instance of a service is avaiable everywhere.

providers: [
BackendService,
HeroService,
Logger
]

  • Register providers in component.
@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
providers: [HeroService]
})

Registering at a component level means you get a new instance of the service with each new instance of that component.

  • Dependency injection is wired into the Angular framework and used everywhere.

  • The injector is the main mechanism.

    • An injector maintains a container of service instances that it created.
    • An injector can create a new service instance from a provider.
  • A provider is a recipe for creating a service.

  • Register providers with injectors.

More

Here is a brief, alphabetical list of other important Angular features and services. Most of them are covered in this documentation (or soon will be).

  • Animations: Animate component behavior without deep knowledge of animation techniques or CSS with Angular’s animation library.

  • Change detection: The change detection documentation will cover how Angular decides that a component property value has changed, when to update the screen, and how it uses zones to intercept asynchronous activity and run its change detection strategies.

  • Events: The events documentation will cover how to use components and services to raise events with mechanisms for publishing and subscribing to events.

  • Forms: Support complex data entry scenarios with HTML-based validation and dirty checking.

  • HTTP: Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.

  • Lifecycle hooks: Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.

  • Pipes: Use pipes in your templates to improve the user experience by transforming values for display. Consider this currency pipe expression:

price | currency:'USD':true

It displays a price of “42.33” as $42.33.

  • Router: Navigate from page to page within the client application and never leave the browser.

  • Testing: Run unit tests with Angular’s testing library on your application parts as they interact with the Angular framework.

Template Syntax

HTML

Template expressions

A template expression produces a value. Angular executes the expression and assigns it to a property of a binding target;

the target might be

  • an HTML element
  • a component
  • a directive.
  1. interpolation - <div></div>
  2. property binding - [property]="expression"

We write template expressions in a language that looks like JavaScript. Many JavaScript expressions are legal template expressions, but not all.

JavaScript expressions that have or promote side effects are prohibited, including:

  • assignments (=, +=, -=, …)
  • new
  • chaining expressions with ; or ,
  • increment and decrement operators (++ and —)

Other notable differences from JavaScript syntax include:

  • no support for the bitwise operators | and &
  • new template expression operators, such as | and ?.

Expression context

The expression context is typically the component instance, which is the source of binding values.

The component itself is usually the expression context, in which case the template expression usually references that component.

The expression context can include objects other than the component. A template reference variable is one such alternative context object.

Expression guidelines

NO VISIBLE SIDE EFFECTS

A template expression should not change any application state other than the value of the target property.

This rule is essential to Angular’s “unidirectional data flow” policy.

We should never worry that reading a component value might change some other displayed value.

The view should be stable throughout a single rendering pass.

QUICK EXECUTION

Expressions should finish quickly or the user experience may drag, especially on slower devices.

SIMPLICITY

A property name or method call should be the norm. An occasional Boolean negation (!) is OK. Otherwise, confine application and business logic to the component itself, where it will be easier to develop and test.

IDEMPOTENCE

In Angular terms, an idempotent expression always returns exactly the same thing until one of its dependent values changes.

Template statements

A template statement responds to an event raised by a binding target such as an element, component, or directive.

(event)="statement"

A template statement has a side effect. It’s how we update application state from user input. There would be no point to responding to an event otherwise.

Responding to events is the other side of Angular’s “unidirectional data flow”. We’re free to change anything, anywhere, during this turn of the event loop.

Like template expressions, template statements use a language that looks like JavaScript.

The template statement parser is different than the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).

certain JavaScript syntax is not allowed:

  • new
  • increment and decrement operators, ++ and —
  • operator assignment, such as += and -=
  • the bitwise operators | and &
  • the template expression operators

Statement context

As with expressions, statements can refer only to what’s in the statement context — typically the component instance to which we’re binding the event.

The onSave in (click)="onSave()" is sure to be a method of the data-bound component instance.

The statement context may include an object other than the component. A template reference variable is one such alternative context object. We’ll frequently see the reserved $event symbol in event binding statements, representing the “message” or “payload” of the raised event.

Statement guidelines

As with expressions, avoid writing complex template statements. A method call or simple property assignment should be the norm.

Binding Syntax

Data direction Syntax Binding type
One-way from data source to view target \{\{expressions\}\} Interpolation
[target]="expression" Property
bind-target = "expression" Attribute
Class
Style
One-way from view target to data source (target)="statement" Event
on-target="statement"
Two-way [(target)]="expression" Two-way
bindon-target="expression"

A new mental model

HTML attribute vs. DOM property

The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.
  • Some HTML attributes don’t have corresponding properties. colspan is one example.
  • Some DOM properties don’t have corresponding attributes. textContent is one example.
  • Many HTML attributes appear to map to properties … but not in the way we might think!

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can’t.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

Template binding works with properties and events, not attributes.

In the world of Angular, the only role of attributes is to initialize element and directive state. When we data bind, we’re dealing exclusively with element and directive properties and events. Attributes effectively disappear.

Binding targets

The target of a data binding is something in the DOM.

Depending on the binding type, the target can be

  • an (element | component | directive) property
  • an (element | component | directive) event
  • an attribute name.
Binding Type Target Examples
Property Element roperty <img [src]="heroImageUrl">
Component property <hero-detail [hero]="currentHero"></hero-detail>
Directive property <div [ngClass]="{selected:isSelected}"></div>
Event Element event <button (click)="onSave()">Save</button>
Component event <hero-detail (deleteRequest)="deleteHero()"></hero-detail>
Directive event <div (myClick)="clicked=$event">click me</div>
Two-way Event and property <input [(ngModel)]="heroName">
Attribute Attribute(the exception) <button [attr.aria-label]="help">help</button>
Class class property <div [class.special]="isSpecial">Special</div>
Sytle style property <button [style.color] = "isSpecial ? 'red' : 'green'">

Property binding

Attribute, class, and style bindings

Event binding

Two-way data binding with NgModel

Built-in directives

NgClass

NgStyle

NgIf

NgSwitch

NgFor

Alias

ws=D: $t IF ".$*." == ".." (cd D:\project/project1) ELSE (cd $*) $t subl .

Copy folder

cp -a folder/subfolder G:/whatever/folder/subfolder

Shortcuts

Tab manipulation

  • Ctrl + ` : Global Summon from taskbar
  • Win + Alt + p : Preferences (Or right click on title bar)
  • Ctrl + t : New tab dialog (maybe you want to open cmd as admin?)
  • Ctrl + w : Close tab
  • Shift + Alt + number : Fast new tab:
    1. CMD
    2. PowerShell
  • Alt + Enter : Fullscreen

Shell

  • Ctrl + Alt + u : Traverse up in directory structure (lovely feature!)
  • End, Home, Ctrl : Traverse text as usual on Windows
  • Ctrl + r : History search
  • Shift + mouse : Select and copy text from buffer
  • Right click / Ctrl + Shift + v : Paste text

Client Server
—> syn=1 seq=x —>
<— ack=x+1 seq=y <—
—> ack=y+1 seq=z —>

Summary:

Equivalent to HTTP status 100. System.Net.HttpStatusCode.Continue indicates
that the client can continue with its request.

Continue = 100,

Summary:

Equivalent to HTTP status 101. System.Net.HttpStatusCode.SwitchingProtocols
indicates that the protocol version or protocol is being changed.

SwitchingProtocols = 101,

Summary:

Equivalent to HTTP status 200. System.Net.HttpStatusCode.OK indicates that
the request succeeded and that the requested information is in the response.
This is the most common status code to receive.

OK = 200,

Summary:

Equivalent to HTTP status 201. System.Net.HttpStatusCode.Created indicates
that the request resulted in a new resource created before the response was
sent.

Created = 201,

Summary:

Equivalent to HTTP status 202. System.Net.HttpStatusCode.Accepted indicates
that the request has been accepted for further processing.

Accepted = 202,

Summary:

Equivalent to HTTP status 203. System.Net.HttpStatusCode.NonAuthoritativeInformation
indicates that the returned metainformation is from a cached copy instead
of the origin server and therefore may be incorrect.

NonAuthoritativeInformation = 203,

Summary:

Equivalent to HTTP status 204. System.Net.HttpStatusCode.NoContent indicates
that the request has been successfully processed and that the response is
intentionally blank.

NoContent = 204,

Summary:

Equivalent to HTTP status 205. System.Net.HttpStatusCode.ResetContent indicates
that the client should reset (not reload) the current resource.

ResetContent = 205,

Summary:

Equivalent to HTTP status 206. System.Net.HttpStatusCode.PartialContent indicates
that the response is a partial response as requested by a GET request that
includes a byte range.

PartialContent = 206,

Summary:

Equivalent to HTTP status 300. System.Net.HttpStatusCode.MultipleChoices
indicates that the requested information has multiple representations. The
default action is to treat this status as a redirect and follow the contents
of the Location header associated with this response.

MultipleChoices = 300,

Summary:

Equivalent to HTTP status 300. System.Net.HttpStatusCode.Ambiguous indicates
that the requested information has multiple representations. The default
action is to treat this status as a redirect and follow the contents of the
Location header associated with this response.

Ambiguous = 300,

Summary:

Equivalent to HTTP status 301. System.Net.HttpStatusCode.MovedPermanently
indicates that the requested information has been moved to the URI specified
in the Location header. The default action when this status is received is
to follow the Location header associated with the response.

MovedPermanently = 301,

Summary:

Equivalent to HTTP status 301. System.Net.HttpStatusCode.Moved indicates
that the requested information has been moved to the URI specified in the
Location header. The default action when this status is received is to follow
the Location header associated with the response. When the original request
method was POST, the redirected request will use the GET method.

Moved = 301,

Summary:

Equivalent to HTTP status 302. System.Net.HttpStatusCode.Found indicates
that the requested information is located at the URI specified in the Location
header. The default action when this status is received is to follow the
Location header associated with the response. When the original request method
was POST, the redirected request will use the GET method.

Found = 302,

Summary:

Equivalent to HTTP status 302. System.Net.HttpStatusCode.Redirect indicates
that the requested information is located at the URI specified in the Location
header. The default action when this status is received is to follow the
Location header associated with the response. When the original request method
was POST, the redirected request will use the GET method.

Redirect = 302,

Summary:

Equivalent to HTTP status 303. System.Net.HttpStatusCode.SeeOther automatically
redirects the client to the URI specified in the Location header as the result
of a POST. The request to the resource specified by the Location header will
be made with a GET.

SeeOther = 303,

Summary:

Equivalent to HTTP status 303. System.Net.HttpStatusCode.RedirectMethod automatically
redirects the client to the URI specified in the Location header as the result
of a POST. The request to the resource specified by the Location header will
be made with a GET.

RedirectMethod = 303,

Summary:

Equivalent to HTTP status 304. System.Net.HttpStatusCode.NotModified indicates
that the client's cached copy is up to date. The contents of the resource
are not transferred.

NotModified = 304,

Summary:

Equivalent to HTTP status 305. System.Net.HttpStatusCode.UseProxy indicates
that the request should use the proxy server at the URI specified in the
Location header.

UseProxy = 305,

Summary:

Equivalent to HTTP status 306. System.Net.HttpStatusCode.Unused is a proposed
extension to the HTTP/1.1 specification that is not fully specified.

Unused = 306,

Summary:

Equivalent to HTTP status 307. System.Net.HttpStatusCode.RedirectKeepVerb
indicates that the request information is located at the URI specified in
the Location header. The default action when this status is received is to
follow the Location header associated with the response. When the original
request method was POST, the redirected request will also use the POST method.

RedirectKeepVerb = 307,

Summary:

Equivalent to HTTP status 307. System.Net.HttpStatusCode.TemporaryRedirect
indicates that the request information is located at the URI specified in
the Location header. The default action when this status is received is to
follow the Location header associated with the response. When the original
request method was POST, the redirected request will also use the POST method.

TemporaryRedirect = 307,

Summary:

Equivalent to HTTP status 400. System.Net.HttpStatusCode.BadRequest indicates
that the request could not be understood by the server. System.Net.HttpStatusCode.BadRequest
is sent when no other error is applicable, or if the exact error is unknown
or does not have its own error code.

BadRequest = 400,

Summary:

Equivalent to HTTP status 401. System.Net.HttpStatusCode.Unauthorized indicates
that the requested resource requires authentication. The WWW-Authenticate
header contains the details of how to perform the authentication.

Unauthorized = 401,

Summary:

Equivalent to HTTP status 402. System.Net.HttpStatusCode.PaymentRequired
is reserved for future use.

PaymentRequired = 402,

Summary:

Equivalent to HTTP status 403. System.Net.HttpStatusCode.Forbidden indicates
that the server refuses to fulfill the request.

Forbidden = 403,

Summary:

Equivalent to HTTP status 404. System.Net.HttpStatusCode.NotFound indicates
that the requested resource does not exist on the server.

NotFound = 404,

Summary:

Equivalent to HTTP status 405. System.Net.HttpStatusCode.MethodNotAllowed
indicates that the request method (POST or GET) is not allowed on the requested
resource.

MethodNotAllowed = 405,

Summary:

Equivalent to HTTP status 406. System.Net.HttpStatusCode.NotAcceptable indicates
that the client has indicated with Accept headers that it will not accept
any of the available representations of the resource.

NotAcceptable = 406,

Summary:

Equivalent to HTTP status 407. System.Net.HttpStatusCode.ProxyAuthenticationRequired
indicates that the requested proxy requires authentication. The Proxy-authenticate
header contains the details of how to perform the authentication.

ProxyAuthenticationRequired = 407,

Summary:

Equivalent to HTTP status 408. System.Net.HttpStatusCode.RequestTimeout indicates
that the client did not send a request within the time the server was expecting
the request.

RequestTimeout = 408,

Summary:

Equivalent to HTTP status 409. System.Net.HttpStatusCode.Conflict indicates
that the request could not be carried out because of a conflict on the server.

Conflict = 409,

Summary:

Equivalent to HTTP status 410. System.Net.HttpStatusCode.Gone indicates that
the requested resource is no longer available.

Gone = 410,

Summary:

Equivalent to HTTP status 411. System.Net.HttpStatusCode.LengthRequired indicates
that the required Content-length header is missing.

LengthRequired = 411,

Summary:

Equivalent to HTTP status 412. System.Net.HttpStatusCode.PreconditionFailed
indicates that a condition set for this request failed, and the request cannot
be carried out. Conditions are set with conditional request headers like
If-Match, If-None-Match, or If-Unmodified-Since.

PreconditionFailed = 412,

Summary:

Equivalent to HTTP status 413. System.Net.HttpStatusCode.RequestEntityTooLarge
indicates that the request is too large for the server to process.

RequestEntityTooLarge = 413,

Summary:

Equivalent to HTTP status 414. System.Net.HttpStatusCode.RequestUriTooLong
indicates that the URI is too long.

RequestUriTooLong = 414,

Summary:

Equivalent to HTTP status 415. System.Net.HttpStatusCode.UnsupportedMediaType
indicates that the request is an unsupported type.

UnsupportedMediaType = 415,

Summary:

Equivalent to HTTP status 416. System.Net.HttpStatusCode.RequestedRangeNotSatisfiable
indicates that the range of data requested from the resource cannot be returned,
either because the beginning of the range is before the beginning of the
resource, or the end of the range is after the end of the resource.

RequestedRangeNotSatisfiable = 416,

Summary:

Equivalent to HTTP status 417. System.Net.HttpStatusCode.ExpectationFailed
indicates that an expectation given in an Expect header could not be met
by the server.

ExpectationFailed = 417,

Summary:

Equivalent to HTTP status 426. System.Net.HttpStatusCode.UpgradeRequired
indicates that the client should switch to a different protocol such as TLS/1.0.

UpgradeRequired = 426,

Summary:

Equivalent to HTTP status 500. System.Net.HttpStatusCode.InternalServerError
indicates that a generic error has occurred on the server.

InternalServerError = 500,

Summary:

Equivalent to HTTP status 501. System.Net.HttpStatusCode.NotImplemented indicates
that the server does not support the requested function.

NotImplemented = 501,

Summary:

Equivalent to HTTP status 502. System.Net.HttpStatusCode.BadGateway indicates
that an intermediate proxy server received a bad response from another proxy
or the origin server.

BadGateway = 502,

Summary:

Equivalent to HTTP status 503. System.Net.HttpStatusCode.ServiceUnavailable
indicates that the server is temporarily unavailable, usually due to high
load or maintenance.

ServiceUnavailable = 503,

Summary:

Equivalent to HTTP status 504. System.Net.HttpStatusCode.GatewayTimeout indicates
that an intermediate proxy server timed out while waiting for a response
from another proxy or the origin server.

GatewayTimeout = 504,

Summary:

Equivalent to HTTP status 505. System.Net.HttpStatusCode.HttpVersionNotSupported
indicates that the requested HTTP version is not supported by the server.

HttpVersionNotSupported = 505,

C# 6.0

Auto Property Initializers

public class Developer
{
public bool DrinksCoffee {get;set;} = true;
}

Dictionary Initializers

var devSkills = new Dictionary<string, bool>();

devSkills["C#"] = true;
devSkills["HTML"] = true;

var devSkills = new Dictionary<string, bool>() {
["C#"] = true,
["VB.NET"] = true,
["HTML"] = true
};

String Interpolation

string test = "test1" + "with " + test2 + " finished.";
string test2 = string.Fromat("{0} {1}, {2} @ {3}", test1, test3, test4, test5);

var testCsharp6 = $"{firstName} {middleName} {lastName} , {jobTitle} @ {Company}";

Null Conditional Operator

public string[] GenerateCoffeeOrder(Coffee[] favCoffee)
{
var order = favCoffee?.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

\?.\

  • “?” If the variable is null, then return null.
  • Otherwise execute whatever is after the “.”

Name of Expression

public string[] GenerateCoffeeOrder(Coffee[] favCoffee)
{
if (favCoffee == null)
{
throw new ArgumentNullException("favCoffee");
}

var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

public string[] GenerateCoffeeOrder(Coffee[] coffeeOrders)
{
if (coffeeOrders == null)
{
throw new ArgumentNullException(nameof(coffeeOrders));
}

var order = coffeeOrders.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

Expression Bodied Functions & Properties

public class Coffee {
public string Name {get;set;}
public string Size {get;set;}
public string OrderDescription => $"{Name} - {Size}";
}

Exception Filters

catch (SqlException ex) when (ex.ErrorCode == -2)
{
return "Timeout Error";
}
catch (SqlException ex) when (ex.ErrorCode == 1205)
{
return "Deadlock occurred";
}
catch (SqlException)
{
return "Unknown";
}

catch (SqlException ex) when (HttpContext.Current.Identity.Name == "Boss Man" || DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday) {
// Do nothing
}

Static Using

public double GetArea(double radius)
{

return Math.PI * Math.Pow(radius, 2);
}

public double GetArea(double radius
{
return PI * Pow(radius, 2)
;

}

Await in Catch and Finally Blocks

Extension Add in Collection Initializers

C# 7.0

Improvements to the Tuple Class

var newTuple = new Tuple<string, decimal, bool>(Name: "A", OrderTotal: 123, IsVIP: true);

Inline output variable

if (int.TryParse("123", out var i)
{
    
}

Pattern matching in ‘switch’

public string SuggestAnAction2(Bird bird) {
    switch (bird):
    {
        case Magpie m when m.IsSwoopingSeason == true:
            return "Bring a helmet";
        case Magpie m when m.IsSwoppingSeason == false:
            return "Go for a stroll";
        case Budgie b:
            return $"Bring {b.FavouriteFood} for the walk";
        case null:
            throw new ArgumentNullException(nameof(bird));
        default:
            return "Do nothing"
    }
}