4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】Null合体演算子でシングルトンパターンを簡潔に書く

Posted at

イマイチNull合体演算子を使うケースの
例として良いものが思い浮かばなかったけど
これだと有用性が分かりやすいと思った例があったので備忘の為に記載。

演算子使用前
class HogeManager
{
    private static HogeManager _instance;

    /// <summary>
    /// インスタンス取得
    /// </summary>
    /// <returns></returns>
    public static HogeManager GetInstance()
    {
        if (null == _instance)
        {
            // Nullの場合だけインスタンス生成
            _instance = new HogeManager();
        }
        return _instance;
    }
}
演算子使用後
class HogeManager
{
    private static HogeManager _instance;

    /// <summary>
    /// インスタンス取得
    /// </summary>
    /// <returns></returns>
    public static HogeManager GetInstance()
    {
        return _instance ?? (_instance = new HogeManager());
    }
}

大分スッキリします。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?