C# Topics (1)

is operator

Console.WriteLine(new A{val1=1,val2=2} is { val1:1 ,val3:0});//true
public class A
{
    public int val1;
    public int val2;
    public int val3;
}

object o=default(object);
o is null //true
o is not null //false

is with patterns

object greeting = "Hello, World!";
if (greeting is string message)
{
    Console.WriteLine(message.ToLower());  // output: hello, world!
}

int? xNullable = 7;
int y = 23;
object yBoxed = y;
if (xNullable is int a && yBoxed is int b)
{
    Console.WriteLine(a + b);  // output: 30
}

with expresion

with expression produces a copy of its operand with the specified properties and fields modified.
it work only with record and struct for class you can use IClonable or serialization and deserialization
you use object initializer syntax to specify what members to modify and their new values:

public record Point(int X, int Y);
public record NamedPoint(string Name, int X, int Y) : Point(X, Y);

public static void Main()
{
   Point p1 = new NamedPoint("A", 0, 0);
   Point p2 = p1 with { X = 5, Y = 3 };
   Console.WriteLine(p2 is NamedPoint);  // output: True
   Console.WriteLine(p2);  // output: NamedPoint { X = 5, Y = 3, Name = A }
}

stackalloc

allocate stacked memory for performance purposes

const int MaxStackLimit = 1024;
Span<byte> buffer = inputLength <= MaxStackLimit ? stackalloc byte[MaxStackLimit] : new byte[inputLength];
Span<int> first = stackalloc int[3] { 1, 2, 3 };
Span<int> second = stackalloc int[] { 1, 2, 3 };
ReadOnlySpan<int> third = stackalloc[] { 1, 2, 3 };

Touples

public class A
{
    public int val1;
    public int val2;
    public int val3;
    
    (int v1,int v2,int v3) GetVal()
    {
        return (val1, val2);
    }
}


 (int t2,int t3) T = (1, 2);

anonymous object

var m = new { m = 12 };

List<int> vals = new(){ 1, 2, 3 };

A aa = new(1,2,3);

A aa = new(){val1=1,val2=2,val3=3};

Record

by default record is a class compares the record with == it compares the properties


record A
{
    public int a { get; init; }
    public int b { get; init; }
}

record AA(int a, int b);

extension method

public static class StringExtensions
{
    public static void GobbleGobble(this string s,int val) //new string("").GobbleGobble(12)
    {
        Console.Out.WriteLine("Gobble Gobble, " + s);
    }
}