Reference · Fondasi C#

C# untuk developer TypeScript

Ringkasan satu halaman. Dari Lesson 0002.

Memilih jenis tipe [1]

DeklarasiSemantik== membandingkanPakai untukPadanan TS
classreferencereferensiPerilaku, state berubah, Entity, Service, Controllerclass / object
structvalue (disalin)tidak ada == bawaanData kecil (±64 byte)seperti number
recordreferencenilai propertiDTO, data immutableReadonly<type> + spread
record structvaluenilai propertiData kecil + equality + with—
interfacekontrak—Kontrak antar layer, DI, mockinterface (tapi nominal)

Value vs reference [1]

var b = a;  // struct: salin data, b.X = 9 tidak mengubah a
            // class : salin referensi, b.X = 9 juga mengubah a
// Value: struct, enum, int, decimal, bool.  Reference: class, array, string, delegate.

Record [3]

public record ProductResponse(int Id, string Name, decimal Price); // properti init-only
a == b                      // True kalau semua properti sama
var c = a with { Price = 3m };  // salinan dangkal (shallow copy) dengan perubahan
// Entity EF Core: JANGAN record, karena EF Core butuh reference equality.

Nullable reference types [4]

C# (<Nullable>enable</Nullable>)TypeScript (strictNullChecks)
string Namename: string
string? Descriptiondescription: string | null
x?.Length, x ?? "-"x?.length, x ?? "-"
x!.Length (null-forgiving, seperlunya)x!.length

Hanya warning compiler. Perilaku runtime tidak berubah, jadi input dari luar tetap divalidasi.

Interface vs abstract class [5]

Jawaban 60 detik

class = reference type, struct = value type (disalin, untuk data kecil). record = modifier di atas keduanya yang memberi value equality, ToString, dan with; positional record class immutable. DTO adalah data murni, jadi ditulis sebagai record. Entity EF Core tetap class karena EF Core butuh reference equality.

Sumber: [1] The C# type system · [2] C# record types · [3] Records (C# reference) · [4] Nullable reference types · [5] Interfaces