Coalesce for VB.Net

Posted by Blake on 2/28/2011
)

Here are two simple functions (4 functions, 2 with 2 overloads) that will create a Coalesce command for VB.Net similar to what exists in SQL. These functions will return the first non null value in either an array of objects or a generic list of objects.

        ''' <summary>
        ''' Returns the first non null value in the object list.  If all objects in the list are null, then a null will be returned.
        ''' </summary>
        ''' <param name="objList"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Coalesce(ByVal objList() As Object) As Object
            For Each o As Object In objList
                If o IsNot Nothing Then
                    Return o
                End If
            Next
            Return New Object
        End Function

        ''' <summary>
        ''' Returns the first non null value in the object list.  If all objects in the list are null, then a null will be returned.
        ''' </summary>
        ''' <param name="objList"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Coalesce(ByVal objList As List(Of Object)) As Object
            For Each o As Object In objList
                If o IsNot Nothing Then
                    Return o
                End If
            Next
            Return New Object
        End Function

        ''' <summary>
        ''' Returns the first non null value in the object list.  If all objects in the list are null the the defaultValue variable specified
        ''' will be returned.
        ''' </summary>
        ''' <param name="objList"></param>
        ''' <param name="defaultValue"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Coalesce(ByVal objList() As Object, ByVal defaultValue As Object) As Object
            For Each o As Object In objList
                If o IsNot Nothing Then
                    Return o
                End If
            Next
            Return defaultValue
        End Function

        ''' <summary>
        ''' Returns the first non null value in the object list.  If all objects in the list are null the the defaultValue variable specified
        ''' will be returned.
        ''' </summary>
        ''' <param name="objList"></param>
        ''' <param name="defaultValue"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function Coalesce(ByVal objList() As List(Of Object), ByVal defaultValue As Object) As Object
            For Each o As Object In objList
                If o IsNot Nothing Then
                    Return o
                End If
            Next
            Return defaultValue
        End Function