# Field vs property vs method

Classes typically contain data. These data can be read or modified through three ways. Here we introduce them, so you know which to use in which scenario.

## Field

:::{wpd} field
:id: Field (computer science)
a variable in a class
:::
```cs
var s1 = new LectureSession
{
    Name = "Industrial Programming",
    StartTime = DateTime.Parse("2025-10-06 13:00"),
    Duration = TimeSpan.FromHours(4),
    StudentCount = 36
};
s1.Duration -= TimeSpan.FromHours(1);
Console.WriteLine(s1.Duration);

public class LectureSession
{
    public TimeSpan Duration;
    public string Name;
    public DateTime StartTime;
    public uint StudentCount;
}
```
Output:
```
03:00:00
```

## Property – for regulating access

Imagine that duration of a `LectureSession` may not be changed after creating it, because it stays the same whole semester. How can we give read access to a field but forbid writing?

It cannot be `private`, because otherwise we cannot read this information, however we also cannot leave it as a `field`, because then we could accidentally modify it. `const` keyword is also not helpful, because `const` requires the variable to be known at compile-time, but each lecture session's duration is determined at runtime when the instance is created.

Properties can help.

:::{wpd} property
:id: Property (object-oriented programming)
a special sort of class member, intermediate in functionality between a field and a method.
:::

In the following example `Duration` becomes a property. Compared to a field, we can control read or write to the variable. For example in the following, `Duration` can only be written during creation, but cannot be modified.
```cs
var s1 = new LectureSession
{
    Name = "Industrial Programming",
    StartTime = DateTime.Parse("2025-10-06 13:00"),
    Duration = TimeSpan.FromHours(4),
    StudentCount = 36
};
s1.Duration -= TimeSpan.FromHours(1);
Console.WriteLine(s1.Duration);

public class LectureSession
{
    public string Name;
    public DateTime StartTime;
    public uint StudentCount;
    public TimeSpan Duration { get; init; }
}
```
Output:
```text
Scratch.cs(8,1): Error CS8852 : Init-only property or indexer 'LectureSession.Duration' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
```

## Property with a backing field – for validation

Using methods we can control access to the variables. For example, a session duration cannot be negative. We can check and throw an error if it is the case as shown in the following example.
```cs
var s1 = new LectureSession
{
    Name = "Industrial Programming",
    StartTime = DateTime.Parse("2025-10-06 13:00"),
    Duration = TimeSpan.FromHours(4),
    StudentCount = 36
};
s1.Duration -= TimeSpan.FromHours(1);
Console.WriteLine(s1.Duration);
s1.Duration -= TimeSpan.FromHours(4);

public class LectureSession
{
    private TimeSpan _duration;
    public string Name;
    public DateTime StartTime;
    public uint StudentCount;

    public TimeSpan Duration
    {
        get => _duration;
        set => _duration = value <= TimeSpan.Zero ? throw new ArgumentException("Duration must be positive") : value;
    }
}
```
Output:
```text
03:00:00
Unhandled exception. System.ArgumentException: Duration must be positive
   at LectureSession.set_Duration(TimeSpan value) in /Scratch.cs:line 22
   at Program.<Main>$(String[] args) in /home/u/projects/ind-prog-code/scratchpad/Scratch.cs:line 10
```

:::{activity}
Augment the last 
:::

## Method


:::{wpd} method
:id: Method (computer programming)
a procedure (function) associated with an object
:::


## Appendix

### `[]` vs `{}`
There is a difference between brackets (`[]`) and curly braces (`{}`):
- `()` used for methods (including constructors and thus also constructor parameters)
- `{}` define a block of code or scope in
  - classes
  - methods
  - loops
  - conditionals
  - object initializers, e.g.,
    
    ```cs
    var s = LectureSession{
        Name = "Industrial Programming",
        StartTime = DateTime.Parse("2025-10-06 13:00"),
        Duration = TimeSpan.FromHours(4),
        StudentCount = 36
    }
    ```
  
So we can use both brackets and braces to initialize data structures.

### Record, struct vs classes

The learning goals of this course can be achieved only with classes, so I left records and structs out.

#### Record

Records are syntactic sugar for **immutable data classes** with the integrated benefits:
- value-based equality
- `toString()`
- cloning

```cs
var s1 = new LectureSession
    ("Industrial Programming", DateTime.Parse("2025-10-06 13:00"), TimeSpan.FromHours(4), 36);
Console.WriteLine(s1);

public record LectureSession(
    string Name,
    DateTime StartTime,
    TimeSpan Duration,
    uint StudentCount
);
```

#### Struct

Structs are class-like containers, but if a struct is assigned, then its values are copied. A class is assigned by reference.

```cs
var s1 = new LectureSession
{
    Name = "Industrial Programming",
    StartTime = DateTime.Parse("2025-10-06 13:00"),
    Duration = TimeSpan.FromHours(4),
    StudentCount = 36
};
Console.WriteLine(s1);

public struct LectureSession
{
    public string Name;
    public DateTime StartTime;
    public TimeSpan Duration;
    public uint StudentCount;
}
```