Return to Snippet

Revision: 52147
at October 14, 2011 16:45 by bryanlyman


Initial Code
Imports System
Imports System.Text
Imports Collections

''' <summary>
''' System Object extensions
''' Originally these were intended to be extenders to the System.Object object,
''' but because in VB.net you cannot extend the System.Object object I changed these to global functions
''' C# allows this because it doesn't have the same late binding restrictions as VB
''' </summary>
''' <remarks>by Bryan Lyman</remarks>
Module Extensions

	''' <summary>
	''' Simple null object checker
	''' </summary>
	''' <returns>True if the object is Nothing or DBNull</returns>
	Public Function IsNullType(ByVal obj As Object) As Boolean
		Return (obj Is Nothing OrElse obj Is DBNull.Value)
	End Function

	''' <summary>
	''' Simple signed value object checker
	''' </summary>
	''' <returns>True if the object type is signed</returns>
	Public Function IsSigned(ByVal obj As Object) As Boolean
		Return (TypeOf obj Is System.ValueType AndAlso (TypeOf obj Is Int32 OrElse TypeOf obj Is Int64 OrElse TypeOf obj Is Int16 OrElse TypeOf obj Is IntPtr OrElse TypeOf obj Is Decimal OrElse TypeOf obj Is SByte))
	End Function

	''' <summary>
	''' Simple empty value object checker
	''' </summary>
	''' <returns>True if the object is empty and is not Nothing</returns>
	Public Function IsEmpty(ByVal obj As Object) As Boolean
		Return (Not IsNullType(obj) AndAlso ( _
		   (TypeOf obj Is String AndAlso DirectCast(obj, String).Length = 0) OrElse _
		   (TypeOf obj Is StringBuilder AndAlso DirectCast(obj, StringBuilder).Length = 0) OrElse _
		   (TypeOf obj Is ICollection AndAlso DirectCast(obj, ICollection).Count = 0) OrElse _
		   (TypeOf obj Is System.Array AndAlso DirectCast(obj, Array).Length = 0) OrElse _
		   (IsSigned(obj) AndAlso obj = -1) OrElse _
		   (TypeOf obj Is System.ValueType AndAlso obj = 0) OrElse _
		   (TypeOf obj Is System.Guid AndAlso DirectCast(obj, Guid) = Guid.Empty) _
		))
	End Function

	''' <summary>
	''' Empty value or null object checker
	''' </summary>
	''' <returns>True if the object is empty or Nothing or DBNull</returns>
	Public Function IsNullTypeOrEmpty(ByVal obj As Object) As Boolean
		Return (IsNullType(obj) OrElse IsEmpty(obj))
	End Function

End Module

'an example of how this makes your life easier

Private Sub Test(ByVal testVar)
   If (IsNullTypeOrEmpty(testVar)) Then
      throw new Exception("Invalid testVar")
   End If
 
   DoSomething(testVar)
End Sub

Initial URL


Initial Description
Because there is no way to use object extenders in vb.net here is an example of how you can get similar functionality. See the C# example for further info.

Initial Title
Global System Object extensions for easier conditionals (VB.net example)

Initial Tags
class, c, Net, extension

Initial Language
VB.NET