うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【C#】クラスを拡張する

static class に public static void Test(this Hoge)
と記述すると既存のクラスの拡張メソッドを作成することができる

例えば string クラスの 拡張メソッドを作りたい場合は以下のように記述する

public static class StringExtension
{
    public static bool NotNullOrEmpty(this string self)
    {
        return !string.IsNullOrEmpty(self);
    }
}

使う側はメソッド呼び出しのように利用すれば問題ありません

var str = string.Empty;
str.NotNullOrEmpty();