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:
| Parameter | Type | Description |
|---|---|---|
| { get; set; } | Auto-Property | Generates private backing field automatically. |
| record | Type Declaration | C# 9 immutable reference type with value-based equality. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C# Inheritance, Virtual Methods, and Interfaces
Derive subclasses, implement interfaces, and override virtual methods in C#.
C# Named and Optional Parameters in Method Definitions
Define flexible C# methods using optional parameters with defaults and named arguments (name: value) for order independence and clarity.
C# Exception Handling: try, catch, finally, and Exception Filters
Catch and handle exceptions with try, catch, finally, and C# exception filters (when).
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.