動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン1: where T : class —参照型のみ許容

出典: C# Generic 制約 (where T : …) — 業務SE が型安全コードを書く5パターンパターン1: where T : class —参照型のみ許容

パターン1: where T : class —参照型のみ許容 (csharp)#5262b3f47b63
// ✅ Tは参照型のみ
public class Cache<T> where T : class
{
    private readonly Dictionary<string, T> _store = new Dictionary<string, T>();
 
    public T Get(string key)
    {
        if (_store.TryGetValue(key, out var value))
            return value;
        return null;  //参照型なのでnull返せる
    }
 
    public void Set(string key, T value)
    {
        _store[key] = value;
    }
}
 
//使い方
var userCache = new Cache<User>();         // OK: Userはクラス
var stringCache = new Cache<string>();     // OK: stringも参照型
// var intCache = new Cache<int>();        // ❌コンパイルエラー: intは値型
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #5262b3f47b63
  • lines: 22
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「パターン1: where T : class —参照型のみ許容」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

9
図鑑トップ