Classes, objects and properties
A class bundles data and the rules for that data into one type; objects are the real instances built from it. Properties are how a class exposes its data safely, and choosing the right kind (full, field keyword, auto, computed, init/required) is the first real OOP skill in C#.
11.1 Class vs object
- A class is a blueprint: it only says every Product has a Name and a Price; it is not a product itself.
- new Product() creates a fresh object in memory from that blueprint; every object has its own data.
- The variable (cooker, bottle) holds a reference to the object (class = reference type).
- OOP idea: data and the rules for that data live together in one place.
- Step 1
1.class Product: blueprint, design only
- Step 2
2.new Product(): a new object in memory
- Step 3
3.cooker, bottle: each object has its own data
- Step 4
4.Variable = reference to the object
11.2 The problem: public fields
C#
var cooker = new Product();cooker.Name = "Pressure Cooker";cooker.Price = 1899;Console.WriteLine(cooker.Price); var bottle = new Product();bottle.Name = "Steel Bottle";bottle.Price = -500;Console.WriteLine(bottle.Price); class Product{ public string Name = ""; public decimal Price;}Output
$ dotnet run1899-500- A public field is an open variable inside the object: any code can set any value at any time.
- A field has no place to write a check like "price must not be below zero".
- We need a member that looks like a field from outside but runs a check inside: a property.
11.3 Full property (get / set with validation)
- Keep the data in a private field (_price) that outside code cannot touch.
- get reads the value, set writes it; inside set, the value keyword is the value being assigned.
- The check lives in set: a negative price throws ArgumentException.
C#
class Product{ private decimal _price; public decimal Price { get { return _price; } set { if (value < 0) throw new ArgumentException( "Negative price"); _price = value; } }}Output
$ dotnet run399Unhandled exception. System.ArgumentException: Negative price at Product.set_Price(Decimal value) at Program.<Main>$(String[] args)11.4 C# 14: the field keyword
- Writing a separate private field for every validated property is boilerplate.
- C# 14 field keyword = a hidden backing field created by the compiler; no private field declared.
- get; stays automatic, and set stores into field after the check. Same output: 399, then the same exception.
C#
class Product{ public decimal Price { get; set { if (value < 0) throw new ArgumentException( "Negative price"); field = value; } }}11.5 Auto and computed properties
- Auto property { get; set; }: no logic needed, the compiler creates the backing field.
- Computed property (=>): no storage of its own; the expression is calculated on every read.
- WithGst adds 18% GST: Price 400 -> 472.00.
C#
var bottle = new Product();bottle.Name = "Steel Bottle";bottle.Price = 400;Console.WriteLine(bottle.WithGst); class Product{ public string Name { get; set; } = ""; public decimal Price { get; set; } public decimal WithGst => Price * 1.18m;}Output
$ dotnet run Gst.cs472.0011.6 init and required
- init replaces set: the value can be given only while the object is being created (e.g. an order Id).
- required: the caller must give this value in the object initializer.
- Assigning later -> CS8852; creating without the value -> CS9035.
C#
var order = new Order{ Id = "ORD-1001", Amount = 2499};Console.WriteLine(order.Id); // order.Id = "ORD-9999";// var empty = new Order(); class Order{ public required string Id { get; init; } public decimal Amount { get; set; }}Output
Order.cs(8,1): error CS8852: Init-only property or indexer 'Order.Id' can only be assigned in an object initializer, ...Order.cs(9,17): error CS9035: Required member 'Order.Id' must be set in the object initializer or attribute constructor.11.7 Warning CS8618 and its 3 fixes
- A non-nullable string property that gets no value at creation -> warning CS8618.
- Ignore it and Name is really null at runtime: p.Name.Length throws NullReferenceException.
Output
Warning.cs(6,19): warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor.Consider adding the 'required' modifier or declaring the property as nullable.Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.C#
var p = new Product { Sku = "SB-750" };Console.WriteLine(p.Name.Length);Console.WriteLine(p.Brand ?? "No brand"); class Product{ public string Name { get; set; } = ""; public string? Brand { get; set; } public required string Sku { get; set; }}Output
$ dotnet run WarningFix.cs0No brand| Fix | Syntax | Use when |
|---|---|---|
| Default value | = "" | An empty value is a sensible start |
| Nullable | string? | No value is a valid case (no brand) |
| required | required string Sku | The caller must always supply it |
11.8 Comparison: kinds of members
| Kind | Syntax | Stores data? | Validation? |
|---|---|---|---|
| Public field | public decimal Price; | Yes | No |
| Full property | get/set + private _price | Yes (private field) | Yes |
| field keyword (C# 14) | set { ... field = value; } | Yes (hidden field) | Yes |
| Auto property | { get; set; } | Yes (hidden field) | No |
| Computed | => Price * 1.18m | No, calculated on read | N/A |
| init / required | { get; init; } | Yes, set once | Set only at creation |
- Step 1
1.Is the value derived from other data? -> computed (=>)
- Step 2
2.Must it never change after creation? -> init (+ required)
- Step 3
3.Does it need a check? -> field keyword property
- Step 4
4.No logic at all? -> auto property
- Step 5
5.Non-nullable without a value? -> fix CS8618
11.9 Checkpoint: computed is recalculated
C#
var bottle = new Product { Price = 100 };Console.WriteLine(bottle.WithGst); bottle.Price = 200;Console.WriteLine(bottle.WithGst); class Product{ public decimal Price { get; set; } public decimal WithGst => Price * 1.18m;}Output
$ dotnet run Quiz.cs118.00236.0011.10 Common mistakes
- A property calling itself: get => Price; set => Price = value; recurses forever -> Stack overflow. Use field (or a private _price).
- Thinking a public field and an auto property are the same: a property is really get/set methods, so a check can be added later without breaking callers.
- Using public fields in models: the .NET JSON serializer serializes only properties by default and ignores public fields.
- Ignoring CS8618: it becomes a NullReferenceException at runtime.
C#
// Wrong: Stack overflowpublic decimal Price{ get => Price; set => Price = value;} // Right: field = hidden backing fieldpublic decimal Price{ get => field; set => field = value;}11.11 5 rules for properties
- Fields private, properties public.
- No logic: auto property; need a check: field keyword property.
- Derived value: computed (=>).
- Set once: init.
- CS8618: fix with a default value, ? or required.
11.12 Interview tips
- Field = raw variable inside the class; property = a pair of get/set accessors that encapsulates a field.
- Properties give control: validation, computed values, init-only; public APIs always expose properties.
- C# 14 field keyword removes the backing-field boilerplate for validated properties.
- init + required = value must be given at creation and can never change afterwards (CS8852 / CS9035).