I continuously check string fields to check if they are null or blank.
if(myString == null || myString.Trim().Length == 0)
{
throw new ArgumentException("Blank strings cannot be handled.");
}
To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understand how extension methods can be added for a class instance but what about adding a static extension method to a class?
if(String.IsNullOrBlank(myString))
{
throw new ArgumentException("Blank strings cannot be handled.");
}
Bill Wagner in More Effective C# recommends against making extension functions work with null instances (pp. 183).
The reason is that extension methods are supposed to look like method calls, and you can't call a method with a
null
instance.You can safely use an extension method on the instance:
Test cases:
It looks a bit weird though, and I would instead figure out why your strings need to be checked for this case so often. If you fix them at the source, you won't have to be so paranoid about them later!
or
With a few tricks, you make it look like you've added to the String class in any one cs file:
(note, this is not an extension method, see my comment).
Then, in some other CS file:
Notice the "desired" syntax of String.IsNullOrBlank(). I'm not necessarily suggesting that you actually do things this way, just pointing out how you could set things up to make your code work.
Can you add static methods to existing classes? The answer is no, and the value would be pretty thin, because you'd still need to know which class name to type first; with extension methods, the advantage is that you start with a variable name and autocompletion shows you things that are applicable to it.
Another point often made is that extension methods should always throw an exception as soon as possible if their first argument is null. However, I think that rule is overkill if the method mentions in its name that it is designed to check for
null
.The real problem you have is that you want to neatly and readably run some code after checking for a null reference. One way to capture that pattern is in my answer to this question.
A bit late. But you can also put the code to throw an exception in an extension method too. I have two methods (for
ArgumentNullException
andNullReferenceException
).nunit tests:
And then use it as: