Quantcast
Viewing latest article 2
Browse Latest Browse All 15

Extensions can make us free from testing against null

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):

string s;
s = null;
s = s.Replace("bla", "alb");

But, if we add the following extension:

publicstaticstring EReplace(thisstring s, string oldValue, string newValue,
    bool ignoreCase)
{
    if (s == null)
        return s;

    if (ignoreCase)
    {
         return Regex.Replace(s, oldValue, newValue, RegexOptions.IgnoreCase);
    }
    return s.Replace(oldValue, newValue);

 and try to excute the code:

string s;
s = null;
s = s.EReplace("bla", "alb",true);

the code will run without any exception.

Conclusion:

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.


Viewing latest article 2
Browse Latest Browse All 15

Trending Articles