/ Published in: C#
.net 3.0+, To create stability in your code, you must check all inputs into a method to make sure they are valid . Often people overlook this step because of laziness, or because they aren't convinced that exceptions and assertions are actually in place to help you instead of cause you a headache. Here are some extensions which can be used to enhance the System.Object class so that their methods are global to all classes; this makes input checking effortless. This is also somewhat generic in nature because the extensions take no class type in to account before they are called, but we can use type checking to perform different boxing (casting) operations. Sadly this cannot be done in VB.net because late binding restrictions do not allow the Object class to be extended (See my VB.Net example for further information).
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Start by creating a system namespace and class, I used the name "Extensions" but any name can be used. The keyword for creating extensions is the "this" operator in the method variable declaration. I also use "static" methods so they can be used on uninstantiated objects. */ namespace System { public static partial class Extensions { public static bool IsNullType(this object obj) { } public static bool IsSigned(this object obj) { } public static bool IsEmpty(this object obj) { return (!IsNullType(obj) && ( (IsSigned(obj) && obj == (ValueType)(-1)) || )); } public static bool IsNullTypeOrEmpty(this object obj) { return (IsNullType(obj) || IsEmpty(obj)); } } } /* An example of how this makes your life easier is checking to see if a string is DBNull or Null or Empty all in one shot in an efficient manner without having to type the long conditional over and over: */ private void Test(string testVar) { if (testVar.IsNullTypeOrEmpty()) DoSomething(testVar); } /* As a further note: you could add interface checking to the IsEmpty extension which checks the "emptiness" of a class you have created if it is not derived from a type that has a way to check this outright. One .net example if this is the Guid class which has an Empty() method. */