C#:C# Classes, Records, and Properties (get; set;)
C#•Classes & Records

C# Classes, Records, and Properties (get; set;)

Learn encapsulation with C# properties and immutable value semantics with C# 9 records.

Syntax

public class User { public string Name { get; set; } } public record Point(int X, int Y);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
{ get; set; }Auto-PropertyGenerates private backing field automatically.
recordType DeclarationC# 9 immutable reference type with value-based equality.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C# locally:

using System;

// Modern C# 9 Record with positional parameters
public record Endpoint(string Host, int Port);

public class ServerNode {
    // Auto-properties with private setter
    public string Hostname { get; private set; }
    public int Port { get; }
    public bool IsOnline { get; set; }

    public ServerNode(string hostname, int port) {
        Hostname = hostname;
        Port = port;
        IsOnline = true;
    }

    public void Display() {
        Console.WriteLine($"Server: {Hostname}:{Port} [{(IsOnline ? "UP" : "DOWN")}]");
    }
}

public class Program {
    public static void Main() {
        var node = new ServerNode("api-node-01", 8080);
        node.Display();

        // Testing record value equality
        var ep1 = new Endpoint("127.0.0.1", 5000);
        var ep2 = new Endpoint("127.0.0.1", 5000);
        Console.WriteLine($"Record value equality: {ep1 == ep2}");
    }
}
Expected Output:
Server: api-node-01:8080 [UP]
Record value equality: True

How It Works: Step-by-Step

  • Line 4: Declares positional record Endpoint with value equality.
  • Lines 6-21: Defines class ServerNode with properties and constructor.
  • Line 30: ep1 == ep2 evaluates to True because records compare by value, not pointer reference.

Key Concepts

  • Auto-properties eliminate boilerplate private backing fields.
  • Records provide built-in value equality, with-expressions, and formatted printing.

Common Mistake: Trying to mutate record properties initialized with positional syntax

Positional records generate init-only properties by default.

❌ Incorrect
ep1.Port = 80; // Compile Error: init-only property cannot be assigned
✅ Correct
var updated = ep1 with { Port = 80 }; // Non-destructive mutation with 'with'

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler