About the author

Miron Abramson
Me
Software Engineer,
CTO at PixeliT
and .NET addicted for long time.
Open source projects:
MbCompression - Compression library

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2014

Creative Commons License

Blog Flux Directory
Technology Blogs - Blog Top Sites

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:

public static string EReplace(this string 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.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: C#
Posted by Miron on Saturday, March 22, 2008 5:32 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Related posts

Comments

Diamond Rings us

Wednesday, April 28, 2010 1:43 PM

Diamond Rings

Great code!