Extension methods is a good feature. For example, consider the following extension method ...
public static string[] ToWordArray( this string str ) { return str.Split( ' ' ); }Usage ...
string s1 = "This is a sentence"; string[] words = s1.ToWordArray();Looking at the usage, it appears to be an instance method call. But this is misleading, when compiled, calls to 'ToWordArray' extension method are transformed by the compiler into static method calls. So the usage above is translated into ...
string s1 = "This is a sentence"; string[] words = string.ToWordArray(s1);So, since this is not an instance call, the run-time will allow null reference to go through, resulting in NullReference exceptions. See the following example ...
string s2 = null; string[] words = s2.ToWordArray(); // will result in exceptionTo avoid such issues, extension methods must test for null parameters. The above extension should be correctly implemented as below ...
public static string[] ToWordArray( this string str ) { if ( str == null ) return null; else if ( str.Length == 0 ) return new string[ 0 ]; else // empty string has 0 words return str.Split( ' ' ); }


0 comments:
Post a Comment