C#•クラスとレコード
C#のクラス、レコード、プロパティ(get; set;)
C# のプロパティによるカプセル化と、C# 9 record による不変な値セマンティクスを学びます。
構文
public class User {
public string Name { get; set; }
}
public record Point(int X, int Y);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| { get; set; } | Auto-Property | 非公開のバッキングフィールドを自動生成します。 |
| record | Type Declaration | 値ベースの等価比較を備えた C# 9 の不変参照型。 |
そのまま実行できるコード例
Compilra で実行可能C# をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
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}");
}
}期待される出力:
Server: api-node-01:8080 [UP] Record value equality: True
動作のしくみ: ステップ解説
- 4行目: 値等価性を持つ位置指定 record Endpoint を宣言します。
- 6〜21行目: プロパティとコンストラクタを備えたクラス ServerNode を定義します。
- 30行目: record はポインタ参照ではなく値で比較されるため ep1 == ep2 は True になります。
重要ポイント
- 自動プロパティにより、定型的なプライベートバッキングフィールドの記述が不要になります。
- record には値等価比較、with 式、整形出力が組み込まれています。
よくある間違い: 位置指定構文で初期化した record のプロパティを変更しようとすること
位置指定 record は既定で init 専用(init-only)プロパティを生成します。
❌ 誤り
ep1.Port = 80; // Compile Error: init-only property cannot be assigned
✅ 正しい例
var updated = ep1 with { Port = 80 }; // Non-destructive mutation with 'with'