School notes / Charles University / Programming in C#

Czech notes

Lecture 2

Download Markdown · Download PDF

v C# můžeme deklarovat typ proměnné jako var, pokud je hned jasné jaký to je typ (neznamená to že tam můžeme uložit cokoliv)

  • používat u třeba Dictionary<string, int>, ale u int se to třeba nehodí

teď už existuje i opačná zkratka: Person p = new();


struct S {
    public int a; // je read write
    public readonly int b; // je jen read only (ta proměnná - ale pokud je to reference, tak ten měnit můžeme)
    //počáteční hodnotu tam může dát konstruktor - ostatní metody (i když je zavoláme z konstruktoru) nemohou měnit readonly proměnnou


    public const int c = 5; // je to compile time constant

}

properties

Autoimplemented properties

public int A { get; set; } // tohle je property - vypadá jako proměnná, ale je to metoda
  • můžeme si naimplementovat vlastní gettery a settery
private int a;
public int Healthpoints { get; set;}
public int maxHealthpoints = 100;

public double HealthpointsPercentage {
    get { return Healthpoints / maxHealthpoints; } // můžeme mít jen getter
    set { Healthpoints = (int)(value * maxHealthpoints); } // můžeme mít jen setter
}

Primary constructors

od C# 12 můžeme mít primární konstruktory

class X(int a, bool b, int s) {
    public int A = a;

    public bool GetBool(){
        return !b;
    }
}

s se zapomene

b je zachycená proměnná, a b je všude kde je použito se b zamění za backing field

u record class se věci v primárním konstruktoru stanou vnitřními proměnnými a jsou immutable

int? je nullable int

můžu se zeptat a is null nebo a == null