posted 7/31/2011 by Raghav Khunger
Today when I was working with one of my C# application I needed to use IsNullOrWhiteSpace method. You must be familiar with String.IsNullOrWhiteSpace which was introduced in .NET 4. But I was using .NET 3.5 for my application so I decided to write the IsNullOrWhiteSpace method as my own custom string extension method. I got the code for IsNullOrWhiteSpace by decompiling the code of String.IsNullOrWhiteSpace of String class in .NET 4 with the help of Telerik Decompiler . Below is the code my extension class having IsNullOrWhiteSpace method. This method is an Extension method, so you will get the same look and feel while using it as you use IsNullOrWhiteSpace method of string class of .NET4. MyConsoleExtensions.cs
using System; namespace MyConsoleExtensions { public static class MyExtensions { public static bool IsNullOrWhiteSpace(this string value) { if (value == null) { return true; } int num = 0; num++; while (num < value.Length) { if (!char.IsWhiteSpace(value[num])) { return false; } } return true; } } }
Now let's test the same with a console program:
using System; using MyConsoleExtensions; namespace MyConsole { internal class Program { private static void Main(string[] args) { string myString = " "; //will return true bool isNullOrWhiteSpace = myString.IsNullOrWhiteSpace(); myString = "this is test "; //will return false isNullOrWhiteSpace = myString.IsNullOrWhiteSpace(); myString = null; //will return true isNullOrWhiteSpace = myString.IsNullOrWhiteSpace(); } } }
After running the above program you will see the output as mentioned as comments in above code. Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18