Coalesce -- Any suggestions on how to improve this?
-
In rewriting a website, I have found it useful to be able to select the first non-empty value from a list, where "empty" is defined as
Nothing
,DBNull.Value
andString.Empty
. The code I wrote looks like this:Public Shared Function Coalesce(ByVal ParamArray Items() As Object) As Object Dim Result As Object = Nothing For Each Obj As Object In Items If Obj IsNot Nothing AndAlso Obj IsNot DBNull.Value Then If Not String.IsNullOrEmpty(Obj.ToString) Then Result = Obj Exit For End If End If Next Return Result End Function
This way, I could write something like this:
Response.Write(Toolbox.Coalesce(DR("TerminatedDate"), "%nbsp;").ToString)
(Yeah, the nbsp is wrong; I couldn't get it to show up otherwise.) The inputs might be various types -- database fields, date variables, strings, etc. The output will almost always be converted into a
String
, but not necessarily. This looks like it should do what I want, but I'm not fully convinced. Any suggestions on how to improve this? -
In rewriting a website, I have found it useful to be able to select the first non-empty value from a list, where "empty" is defined as
Nothing
,DBNull.Value
andString.Empty
. The code I wrote looks like this:Public Shared Function Coalesce(ByVal ParamArray Items() As Object) As Object Dim Result As Object = Nothing For Each Obj As Object In Items If Obj IsNot Nothing AndAlso Obj IsNot DBNull.Value Then If Not String.IsNullOrEmpty(Obj.ToString) Then Result = Obj Exit For End If End If Next Return Result End Function
This way, I could write something like this:
Response.Write(Toolbox.Coalesce(DR("TerminatedDate"), "%nbsp;").ToString)
(Yeah, the nbsp is wrong; I couldn't get it to show up otherwise.) The inputs might be various types -- database fields, date variables, strings, etc. The output will almost always be converted into a
String
, but not necessarily. This looks like it should do what I want, but I'm not fully convinced. Any suggestions on how to improve this?I wrote an extension method for this not too long ago.
<System.Runtime.CompilerServices.Extension()> _
Public Function GetColumnAsString(ByVal rdr As System.Data.IDataReader, ByVal columnName As String, Optional ByVal valueIfNull As String = "") As String
Dim obj As ObjectIf rdr Is Nothing Then Return valueIfNull Else obj = rdr(columnName) If obj IsNot Nothing AndAlso obj.Equals(DBNull.Value) = False Then Return obj.ToString() Else Return valueIfNull End If End If End Function
Note: it does not check for make sure the column specified exists. Using your example it would be
Response.Write(DR.GetColumnAsString("TerminatedDate", "%nbsp;"))
You could also embed it for more of a coalesce functionality.
Response.Write(DR.GetColumnAsString("TerminatedDate", DR.GetColumnAsString("SomeOtherDate", "%nbsp;"))