Hi,
Today i'm talking about the method IsNullOrEmpty that already exists on System.String class.
We often need to use it on other types of objects like :
- StringBuilder
- All types of Collection that implementes ICollection
- Generic Collections
- Streams
- ...
So in order to solve that issue here is a few set of IsNullOrEmpty Extension Method.
public static Boolean IsNullOrEmpty(this Stream str)
{
if (str == null)
return true;
return (str.Length <= 0);
}
public static Boolean IsNullOrEmpty(this Bitmap value)
{
if (value == null)
return true;
return value.Size.IsEmpty;
}
public static Boolean IsNullOrEmpty(this IEnumerable col)
{
if (col == null)
return true;
Int32 Count = 0;
foreach (var item in col)
{
Count++;
break;
}
return Count <= 0;
}
public static Boolean IsNullOrEmpty(this StringBuilder sb)
{
if (sb == null)
return true;
if (sb.Length <= 0)
return true;
return false;
}
Sample tests :
class Program
{
static void Main(string[] args)
{
IList<Int32> list = new List<Int32>();
Console.WriteLine(list.IsNullOrEmpty());
// Return True;
list.Add(10);
Console.WriteLine(list.IsNullOrEmpty());
// Return False;
StringBuilder sb = new StringBuilder();
Console.WriteLine(sb.IsNullOrEmpty());
// Return True;
sb.Append("TEST");
Console.WriteLine(sb.IsNullOrEmpty());
// Return False;
using (MemoryStream str = new MemoryStream())
{
Console.WriteLine(str.IsNullOrEmpty());
// Return True;
byte[] buffer = new byte[2] { 0x12, 0x12 };
str.Write(buffer, 0, 2);
Console.WriteLine(str.IsNullOrEmpty());
// Return False;
}
Dictionary<String, String> dic = new Dictionary<string, string>();
Console.WriteLine(dic.IsNullOrEmpty());
// Return True;
dic.Add("KEY", "VALUE");
Console.WriteLine(dic.IsNullOrEmpty());
// Return False;
}
}
Hope this help's!
PS : This will comes in the next release of the Sb2.Extensions Library wich is currently in version 1.0.
Views(1621)
-Story-with-C.aspx)
