Saturday, May 20, 2023

C# 10 in a nut shell note.txt

 1.

//download https://www.linqpad.net/

dotnet new console -n MyFirstProgram //cannot use Console

cd MyFirstProgram

dotnet run MyFirstProgram 

//or run the below if just want to build without running

dotnet build MyFirstProgram.csproj


2. All C# types fall into the following categories:

Value types, Reference types, Generic type parameters, Pointer types


3.

Indices: char secondToLast = vowels[^2];

Ranges: Ranges let you "slic" an array: char[] lastThree = vowels[2..];

C# supports "ref" and "out", "in" (cannot be modifierd by the method), "params" modifier for the parameters.

Also can have default value, named arguments

Ref Locals: int[] numbers = {0,1,2,3,4}; ref int numRef = ref numbers[2]; when we modify numRef, we modify the array element

string s1 = null;

string s2 = s1 ?? "nothing"; /s2 evaluates to "nothing"

myVariable ??= someDefault; //equivalent to if(myVariable ==null) myVariable = someDefault;

StringBuilder sb = null;

string s = sb?.ToString(); //No error; s instead evaluates to null

string s = sb?.ToString().ToUpper();//No error; s instead evaluates to null

string foo = null;

char? c = foo?[1];//c is null

switch on types: switch(x) { case int i: ... case string s:...case bool b when b == true: ... default:...}

readonly prevents change after construction: static readonly DateTime StartupTime = DateTime.Now;

const: evalution occus at compile time: public const string Message = "Hello World"; const can also be declared local to a method.

local method: you can define a method within another method.

Deconstruct has one or more out parameters.

var rect = new Rectangle(3,4);

(float width,float height) = rect; or var (width, height) = rect;

Bunny b1 =  new Bunny{Name="Bo, LikesCarrots=true};

A static constructor executes once per type than once per instance. A type can define only one static constructor, and

must be parameterless.

You can also define module initializer which execute once per assembly.

Finilizers are class-only methods before the garbage collector reclaims the memory for an unreferenced object. //difference with deconstruct

partial types and partial methods


4.

int count = 123;

string name = nameof (count);

Asset a = new Asset();

Stock s = a as Stock;// s is null; no exception thrown

You can introduce a variable while using the is operator:

if (a is Stock s) Console.WriteLine(s.SharedOwned);

virtual->override

abstract->override

sealed: prevcent being override

GetType is evaluated at runtime, typeof is evaluated statically at compile time.



No comments:

Post a Comment