LoginSignup
10
9

More than 5 years have passed since last update.

【C#】nullチェックを楽にする演算子のオーバーロード

Posted at

Unity界隈ではおなじみの
UnityEngine.Objectを継承しているオブジェクトの

if (obj) { ... }

というnullチェックの書き方ですが
こんな感じで演算子のオーバーロードすると実装できます


public class Hoge
{
    public static implicit operator bool(Hoge self)
    {
        return self != null;
    }

    public static bool operator true(Hoge self)
    {
        return self != null;
    }

    public static bool operator false(Hoge self)
    {
        return self == null;
    }
}
public class Main
{
    private Hoge hoge;

    public Main(object[] args)
    {
        if (hoge) { Console.WriteLine(hoge.ToString()); }
    }
}
10
9
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
10
9