拡張メソッドと null
昨日は拡張メソッドの闇の面中心に書いたので、今度は光の面でも。
拡張メソッドの紹介記事によく出てくる string.IsNullOrEmpty() ですが、おもしろいことに気付きました。
using System; class Program { static void Main( string[] args ) { string a = "test"; Console.WriteLine( a.IsNullOrEmpty() ); string b = string.Empty; Console.WriteLine( b.IsNullOrEmpty() ); string c = null; Console.WriteLine( c.IsNullOrEmpty() ); // Console.WriteLine( c.ToString() ); // NullReferenceException // Console.WriteLine( null.IsNullOrEmpty() ); // Operator '.' cannot be applied to operand of type '<null>' Console.ReadKey(); } } static class Ext { public static bool IsNullOrEmpty( this string str ) { return string.IsNullOrEmpty( str ); } }
string c = null ってしといて、c.IsNullOrEmpty() が呼べてしまいます! null で呼べるんです。普通のインスタンスメソッドだと NullReferenceException が出てしまうけど、拡張メソッドだと動いてしまいます。これも引数と this になるものの違いですね。なお、露骨に null で null.IsNullOrEmpty() と呼ぼうとしたら、コンパイルエラーになりました。
ハックに使えそうな機能ですねw