The concept of the Extensions in the last frameworks is great. They are extremely easy to write and use, give us infinit options to add needed methods we just wished to have in the framework, and the thing that most catched my eyes is the fact that the extensions are "attached" to an instance of an object, but can be excute with a 'null' object. It is kind of weird.
Excuting the following code will thow an exception (of course):
s = null;
s = s.Replace("bla", "alb");
But, if we add the following extension:
public static string EReplace(this string s, string oldValue, string newValue,
if (s == null)
return Regex.Replace(s, oldValue, newValue, RegexOptions.IgnoreCase);
return s.Replace(oldValue, newValue);
and try to excute the code:
s = null;
s = s.EReplace("bla", "alb",true);
the code will run without any exception.
Using extensions and validate input, will make us free from testing against null any object before excuting a method, and this way, avoid errors that can be throw exceptions on runtime environment.