Wednesday, February 10, 2010

Use .NET Built-in Methods to Save Time and Headaches

During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.

In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.

Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.
Code Block #1 – Check string for nullity or emptiness

NOT Recommended

str = "something"
if (str == null || str == String.Empty)
{
// Oh no! the string isn't valid!
}

Recommended

str = "something"
if (String.IsNullOrEmpty(str))
{
// Oh no! the string isn't valid!
}

Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)

NOT Recommended

str = "something"
if (str == null || str.Trim() == String.Empty)
{
// Oh no! the string isn't valid!
}

Recommended (C# 4.0 Only)

str = "something"
if (String.IsNullOrWhiteSpace(str))
{
// Oh no! the string isn't valid!
}

Read more: IronShay

Posted via email from jasper22's posterous