473,403 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Checking for DBNull with generics

We currently have lots of checks in our businesslayer object's Load()
functions that look like:

If drCourse("txtTTMCnotes").Equals(DBNull.Value) Then
Me._txtTTMCnotes = ""
Else
Me._txtTTMCnotes = CStr(drCourse("txtTTMCnotes"))
End If

and

If drCourse("datTTMCarchived").Equals(DBNull.Value) Then
Me._datTTMCarchived = New Nullable(Of DateTime)
Else
Me._datTTMCarchived = CDate(drCourse("datTTMCarchived"))
End If

I'd like to tidy these up with a a static generic function that will check
for null, and then return either the value or a default value (e.g. int=0,
string="", nullables=new nullable) but am having problems with the return
type. I started with this:

Public Shared Function CheckDbNull(Of T)(ByVal pReaderVar As Object) As T
If pReaderVar.Equals(DBNull.Value) Then
Return Nothing
Else
Return CType(pReaderVar, T)
End If
End Function

Which works, but returns nothing, which is causing null reference
exceptions. I tried writing it like:

If pReaderVar.Equals(DBNull.Value) Then
Select Case GetType(T).FullName
Case "System.String"
Return ""
Case "System.Int32"
Return 0
' etc
End Select

But this doesn't compile, as the return type is not T. Also trying to use
e.g. Return CType("", T) doesn't work.

Does anyone know how to return a specific type based on the return type, or
do I have to create a separate function for each type I'm checking for?

Mar 31 '08 #1
5 1734
Why not obtain the ordinal of the column (GetOrdinal), then use
IsDBNull to check for null on the column, then finally default(T)* to
use the default value for that type. The only exception you might want
here is string (since it looks like you want "") - although personally
I'd find the null more correct, since you can differentiate between
the null string and the empty string.

(*=this is the C# syntax; I'm sure there is a VB equivalent, but I
don't know what it is ;-p)

Re casting the string (as an exception) - I don't know enough about
VB, but in C# you can trick it by doing something like:
return (T)(object)"";

Marc
Mar 31 '08 #2
Just for the record, string-compare on GetType is a nasty way to do things -
surely comparing just the types [i.e. GetType(T) vs GetType(String) etc]
would be cleaner? Granted: you can't do this in a switch... but If, ElseIf,
etc should do.

I'm also a little confused as to what the Nullable<booletc is doing; it
*looks* like it is converting an empty Nullable<boolto object (which
should yield null due to the boxing rules), then converting that null to a
T, which we already know if Nullable<bool(hence becoming another empty
Nullable<bool>)- so we've got a complicated way of saying "null". In C#,
default(T) here would the same thing... I don't know what VB does, though.

Marc
Mar 31 '08 #3
"Marc Gravell" <ma**********@gmail.comwrote in message
news:uz****************@TK2MSFTNGP03.phx.gbl...
Just for the record, string-compare on GetType is a nasty way to do
things - surely comparing just the types [i.e. GetType(T) vs
GetType(String) etc] would be cleaner? Granted: you can't do this in a
switch... but If, ElseIf, etc should do.
Yes, that's why I was doing a string compare. Perhaps I should rewrite it as
you suggest for performance.
I'm also a little confused as to what the Nullable<booletc is doing; it
*looks* like it is converting an empty Nullable<boolto object (which
should yield null due to the boxing rules), then converting that null to a
T, which we already know if Nullable<bool(hence becoming another empty
Nullable<bool>)- so we've got a complicated way of saying "null". In C#,
default(T) here would the same thing... I don't know what VB does, though.
I just checked this and it seems to work fine. It creates a new nullable(of
boolean) with no value, and HasValue = false. Is this different in C#?
*Leon checks
OK, I just tried:

public static T CheckDBNull<T>(object pReaderVar)
{
if (pReaderVar.Equals(DBNull.Value))
{
if (typeof(T) == typeof(string))
{
return (T)(object)"";
}
else if (typeof(T) == typeof(Nullable<bool>))
{
return (T)(object)new Nullable<bool>();
}
else
{
return default(T);
}
}
else
{
return (T)pReaderVar;
}
}

and yes, it returns null for a Nullable<bool>. I wonder why it's different
for VB.NET? Would be interesting to look at the MSIL.

Mar 31 '08 #4

"Leon Mayne" <le**@rmvme.mvps.orgwrote in message
news:C5**********************************@microsof t.com...
Would be interesting to look at the MSIL.
I just did this, and it looks like the VB version is using a different call
to unbox the object:

VB:
IL_00b9: box valuetype [mscorlib]System.Nullable`1<bool>
IL_00be: call !!0
[Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions ::ToGenericParameter<!!0>(object)

C#:
IL_0066: box valuetype [mscorlib]System.Nullable`1<bool>
IL_006b: unbox.any !!T

So the Conversions::ToGenericParameter works but the direct unboxing
doesn't.

Mar 31 '08 #5
"Leon Mayne" <le**@rmvme.mvps.orgwrote in message
news:B2**********************************@microsof t.com...
>
"Leon Mayne" <le**@rmvme.mvps.orgwrote in message
news:C5**********************************@microsof t.com...
>Would be interesting to look at the MSIL.

I just did this, and it looks like the VB version is using a different
call to unbox the object:

VB:
IL_00b9: box valuetype [mscorlib]System.Nullable`1<bool>
IL_00be: call !!0
[Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions ::ToGenericParameter<!!0>(object)

C#:
IL_0066: box valuetype [mscorlib]System.Nullable`1<bool>
IL_006b: unbox.any !!T

So the Conversions::ToGenericParameter works but the direct unboxing
doesn't.
Just tried it myself:

Return
Microsoft.VisualBasic.CompilerServices.Conversions .ToGenericParameter(Of
T)(New Nullable(Of Boolean))

Works fine in VB.NET, but not in C#:

return
Microsoft.VisualBasic.CompilerServices.Conversions .ToGenericParameter<T>(new
Nullable<Boolean>());

Something odd going on here!

Mar 31 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: sashan | last post by:
I'm a Python newbie. I have been using c++ for 5 years and before that I was programming in Pascal. The one thing that annoys me about python is dynamic typing because I find myself making...
6
by: Web Developer | last post by:
Hi, I come across the term "type checking" very often in my readings on C++, and have never heard it in Java. Besides the simplistic answer that it checks the "type", what more does it mean? ...
3
by: JackO | last post by:
I have a text box on a form “txtExamDate” that I know contains nothing. I am trying to test code that will determine the text box is nothing. I am getting the error because there is no value...
1
by: excelleinc.com | last post by:
Hi, I'm trying to check if field contains NULL value in MSSQl 2000 database but keep receiving error. asp.net code: If Trim(HLSQLDSet.Tables("mfglinks").Rows(15).Item(0)) Is Null Then...
1
by: G Dean Blake | last post by:
I read in an earlier post that this would work: If Not myrow.DeletedByUser Is DBNull.Value Then But it gets a diagnostic if DeletedByUser is a boolean. How can I check to see if a boolean is...
7
by: Vayse | last post by:
i want to check if the following field is null. Dim rsAssets As New ADODB.Recordset rsAssets.Fields("SubIcon").Value) IsNull is no longer supported, so what should I use? Thanks
3
by: Antony Sequeira | last post by:
Hi I was trying to improve my understanding of generics. Reading the tutorial http://java.sun.com/docs/books/tutorial/extra/generics/methods.html I had a doubt and wanted to check it out. I...
3
by: John | last post by:
Hi I am using a oledb reader to read from a table. The problem is that system generates an exception when MyReader.GetValue(2) returns a value of type system.dbnull. The system does not allow me...
5
by: bob | last post by:
Hi, i want to check whether the textbox of the detailsview is not left empty, in insert mode. I did this: Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.