Reference · Fondasi C#
C# untuk developer TypeScript
Ringkasan satu halaman. Dari Lesson 0002.
Memilih jenis tipe [1]
| Deklarasi | Semantik | == membandingkan | Pakai untuk | Padanan TS |
|---|---|---|---|---|
class | reference | referensi | Perilaku, state berubah, Entity, Service, Controller | class / object |
struct | value (disalin) | tidak ada == bawaan | Data kecil (±64 byte) | seperti number |
record | reference | nilai properti | DTO, data immutable | Readonly<type> + spread |
record struct | value | nilai properti | Data kecil + equality + with | — |
interface | kontrak | — | Kontrak antar layer, DI, mock | interface (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 Name | name: string |
string? Description | description: 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]
- Interface: kontrak tanpa instance field/constructor. Satu class boleh banyak interface. Contoh:
IProductRepository. - Abstract class: tidak bisa di-
new; boleh punya field, constructor, method jadi. Hanya satu base class per class. Contoh:RepositoryBase<T>.
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