Alan Northam : Casting, ADO.NEThttp://devlicio.us/blogs/alan_northam/archive/tags/Casting/ADO.NET/default.aspxTags: Casting, ADO.NETenCommunityServer 2008.5 SP1 (Build: 31106.3070)ADO.NET, Nullable Types, Casting DBNull and Youhttp://devlicio.us/blogs/alan_northam/archive/2008/03/06/ado-net-nullable-types-casting-dbnull-and-you.aspxFri, 07 Mar 2008 06:21:00 GMT40756a8b-6212-4073-9d98-6c26781577de:39575anortham10<p>I know this may be a little too scary for some of you so I apologize in advance.&nbsp; Take a deep breath and try to imagine that you can&#39;t use NHibernate and you&#39;re stuck using ADO.NET (circa 2001, did they even have computers back then?).&nbsp;</p>
<p>If you&#39;ve ever tried to read the value from a column in a datarow, you&#39;ve probably run into something like this (a quick Google search will bring up page after page of variations):</p>
<p>
myValue = (int)row[&quot;ColumnName&quot;]; //wait, what if it&#39;s null?
if( row[&quot;ColumnName&quot;] == DBNull.Value)
myValue = 0; //or maybe null if myValue is nullable int?
else
myValue = Convert.ToInt32(row[&quot;ColumnName&quot;]);
//lot of code for something simple, hope I don&#39;t have to do this too many times...
//what about
if(row.IsNull(&quot;ColumnName&quot;))
//blah blah blah
</p>
<p>
Wow, that&#39;s ugly. What if I have several nullable columns? What if I have a lot of nullable columns? There has to be a better way.
</p>
<p>Let&#39;s suppose I have a class MyClass (original huh?) and it has a nullable DateTime property and a nullable integer property.
<br />
//snip from MyClass
public DateTime? Property1;
public int? Property2;
//end snip
//some contrived ado.net code
List&lt;MyClass&gt; list = new List&lt;MyClass&gt;();
foreach(DataRow row in dataTable.Rows)
{
MyClass instance = new MyClass();
instance.Property1 = row[&quot;Column1&quot;] as DateTime?;
instance.Property2 = row[&quot;Column2&quot;] as int?;
list.Add(instance);
}
</p>
<p>
<br />
I like a good one line solution.&nbsp; Of course, you really can&#39;t cast DBNull.Value (which would be the value of row[&quot;ColumnX&quot;]&nbsp; if the column is null in the database) as a nullable int (or DateTime?).&nbsp; (edit: thanks Chris) The cast above is actually failing but casting with &quot;as&quot; doesn&#39;t throw an exception and returns a null value which is just what we want.</p>
<p>&quot;as&quot;... you&#39;re my hero...*sniff*&nbsp;</p>
<p>&nbsp;</p><div style="clear:both;"></div><img src="http://devlicio.us/aggbug.aspx?PostID=39575" width="1" height="1">CastingADO.NETNullable Types