<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Alan Northam : Casting</title><link>http://devlicio.us/blogs/alan_northam/archive/tags/Casting/default.aspx</link><description>Tags: Casting</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>ADO.NET, Nullable Types, Casting DBNull and You</title><link>http://devlicio.us/blogs/alan_northam/archive/2008/03/06/ado-net-nullable-types-casting-dbnull-and-you.aspx</link><pubDate>Fri, 07 Mar 2008 03:21:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:39575</guid><dc:creator>anortham</dc:creator><slash:comments>10</slash:comments><description>&lt;p&gt;I know this may be a little too scary for some of you so I apologize in advance.&amp;nbsp; Take a deep breath and try to imagine that you can&amp;#39;t use NHibernate and you&amp;#39;re stuck using ADO.NET (circa 2001, did they even have computers back then?).&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If you&amp;#39;ve ever tried to read the value from a column in a datarow, you&amp;#39;ve probably run into something like this (a quick Google search will bring up page after page of variations):&lt;/p&gt;
&lt;p&gt;
myValue = (int)row[&amp;quot;ColumnName&amp;quot;]; //wait, what if it&amp;#39;s null?
if( row[&amp;quot;ColumnName&amp;quot;] == DBNull.Value)
    myValue = 0; //or maybe null if myValue is nullable int?
else
    myValue = Convert.ToInt32(row[&amp;quot;ColumnName&amp;quot;]); 
//lot of code for something simple, hope I don&amp;#39;t have to do this too many times...
//what about
if(row.IsNull(&amp;quot;ColumnName&amp;quot;))
//blah blah blah
&lt;/p&gt;
&lt;p&gt;
Wow, that&amp;#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.
&lt;/p&gt;
&lt;p&gt;Let&amp;#39;s suppose I have a class MyClass (original huh?) and it has a nullable DateTime property and a nullable integer property.  
&lt;br /&gt;
//snip from MyClass
public DateTime? Property1;
public int? Property2;
//end snip
//some contrived ado.net code
List&amp;lt;MyClass&amp;gt; list = new List&amp;lt;MyClass&amp;gt;();
foreach(DataRow row in dataTable.Rows)
{
    MyClass instance = new MyClass();
    instance.Property1 = row[&amp;quot;Column1&amp;quot;] as DateTime?;
    instance.Property2 = row[&amp;quot;Column2&amp;quot;] as int?;
    list.Add(instance);
}
&lt;/p&gt;
&lt;p&gt;
&lt;br /&gt;
I like a good one line solution.&amp;nbsp; Of course, you really can&amp;#39;t cast DBNull.Value (which would be the value of row[&amp;quot;ColumnX&amp;quot;]&amp;nbsp; if the column is null in the database) as a nullable int (or DateTime?).&amp;nbsp; (edit: thanks Chris) The cast above is actually failing but casting with &amp;quot;as&amp;quot; doesn&amp;#39;t throw an exception and returns a null value which is just what we want.&lt;/p&gt;
&lt;p&gt;&amp;quot;as&amp;quot;... you&amp;#39;re my hero...*sniff*&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=39575" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Casting/default.aspx">Casting</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/ADO.NET/default.aspx">ADO.NET</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Nullable+Types/default.aspx">Nullable Types</category></item><item><title>Databinding performance tip in ASP.NET</title><link>http://devlicio.us/blogs/alan_northam/archive/2007/10/08/databinding-performance-tip-in-asp-net.aspx</link><pubDate>Mon, 08 Oct 2007 15:14:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38637</guid><dc:creator>anortham</dc:creator><slash:comments>5</slash:comments><description>&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; In my &lt;a href="http://devlicio.us/blogs/alan_northam/archive/2007/10/07/casting-options-in-c.aspx" target="_blank"&gt;last post&lt;/a&gt; I mentioned the use of C style casting when databinding in ASP.NET.&amp;nbsp;&amp;nbsp;That got me thinking about the performance differences between the two main ways to bind data in controls with custom templates (GridView, DataList, Repeater, etc).&amp;nbsp; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; In my example I&amp;#39;m using a DataList and by default, Visual Studio will bind the data to your template controls using the &amp;quot;Eval&amp;quot; method.&lt;/p&gt;
&lt;p&gt;&amp;lt;asp:Label ID=&amp;quot;FirstNameLabel&amp;quot; runat=&amp;quot;server&amp;quot; Text=&amp;#39;&amp;lt;%# Eval(&amp;quot;FirstName&amp;quot;) %&amp;gt;&amp;#39;&amp;gt;&amp;lt;/asp:Label&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; This method uses reflection and can be considerably slower depending on the complexity of your template and the number of properties you are binding.&amp;nbsp; The attached code uses a very simple DataList with simple data.&amp;nbsp; To see the difference in performance you&amp;#39;ll need to increase the size of the data using the&amp;nbsp;drop down list&amp;nbsp;at the top.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Compare the performance using&amp;nbsp;the &amp;quot;Eval&amp;quot;&amp;nbsp;method to using the C style cast to access your object&amp;#39;s properties.&lt;/p&gt;
&lt;p&gt;&amp;lt;asp:Label ID=&amp;quot;FirstNameLabel&amp;quot; runat=&amp;quot;server&amp;quot; Text=&amp;#39;&amp;lt;%# ((Person)DataBinder.GetDataItem(Container)).FirstName %&amp;gt;&amp;#39;&amp;gt;&amp;lt;/asp:Label&amp;gt; &lt;/p&gt;
&lt;p&gt;EDIT:&amp;nbsp; As Bill pointed out in the comments, the call to DataBinder.GetDataItem() isn&amp;#39;t necessary as you have access through the container already.&amp;nbsp; I&amp;#39;ve updated the attached test code to include all three methods.&amp;nbsp; These last two being equal in performance in my testing.&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;&amp;lt;asp:Label ID=&amp;quot;FirstNameLabel&amp;quot; runat=&amp;quot;server&amp;quot; Text=&amp;#39;&amp;lt;%# ((Person)Container.DataItem).FirstName %&amp;gt;&amp;#39;&amp;gt;&amp;lt;/asp:Label&amp;gt; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; In my testing this method (the last two methods, actually)&amp;nbsp;was (were)&amp;nbsp;3 - 4 times faster.&amp;nbsp; As I said, this depends on the complexity of your control.&amp;nbsp; &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38637" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us" length="35842" type="application/x-zip-compressed" /><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Casting/default.aspx">Casting</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Databinding/default.aspx">Databinding</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/ASP.NET/default.aspx">ASP.NET</category></item><item><title>Casting options in C#</title><link>http://devlicio.us/blogs/alan_northam/archive/2007/10/07/casting-options-in-c.aspx</link><pubDate>Sun, 07 Oct 2007 19:27:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38628</guid><dc:creator>anortham</dc:creator><slash:comments>9</slash:comments><description>&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; What is the best way to cast from one type to another in C#?&amp;nbsp; This question came up at work last week while I was looking through some older code.&amp;nbsp; The code in question was using the C style casting syntax.&amp;nbsp; I have started to use the &amp;quot;as&amp;quot; style cast more often and rewrote it.&amp;nbsp; Then I decided to do some research into the differences between the two styles to find out if one really is better than the other.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; The most obvious difference is that a C style case will throw and exception if the cast fails and the &amp;quot;as&amp;quot; style cast will simply return null.&amp;nbsp; So first you need to take into consideration what these differences will have on your code.&amp;nbsp; Will you need to wrap every cast in try/catch blocks?&amp;nbsp; Not if you use the &amp;quot;as&amp;quot; style, but you will need to check for null.&amp;nbsp; What about performance?&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; I read a dozen or so blog posts on the subject and they seemed to be pretty evenly divided with half insisting that one style was obviously superior and the other half convinced their chosen style was better.&amp;nbsp; That didn&amp;#39;t really help so I decided to do some testing on my own.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; I&amp;#39;ve attached a small test project for reference, it will allow you to select the number of casts to perform and the style and return the total time and average for each cast.&amp;nbsp; First let&amp;#39;s see what the difference looks like in IL (o is of type object in these examples).&lt;/p&gt;
&lt;p&gt;

((Person) o).Name
becomes:
IL_0036:  castclass  CastTest.Person
Person p = o as Person;
becomes:
IL_0036:  isinst     CastTest.Person
&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;So there is a difference at the IL level but is one a better performer?&amp;nbsp; I wrote three different test projects, the last of which you will find attached to this post.&amp;nbsp; Why did I write three?&amp;nbsp; Because with each test I was convinced that my results must be skewed because I was not seeing the&amp;nbsp; performance difference I expected.&amp;nbsp; I ran test casting 100,000, 1,000,000, 10,000,000 and 100,000,000 objects many times in difference orders, restarting the application between tests, not restarting between tests, clicking the button with my left hand, clicking with my right hand, every combination I could think of.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; What did I discover?&amp;nbsp; It was pretty anticlimactic.&amp;nbsp; In my opinion the difference was completely negligible.&amp;nbsp; That is, negligible if you aren&amp;#39;t throwing exceptions when casting with the C style cast.&amp;nbsp; The most stable set of test results I could get were casting 1,000,000 objects.&amp;nbsp; In this case, either style averaged 10.1 seconds total and averaged 0.0101 milliseconds.&amp;nbsp; We&amp;#39;re talking about a difference of 0.00005 milliseconds per cast.&amp;nbsp; I can&amp;#39;t really get worked up over that.&amp;nbsp; Of course, if you throw exceptions for each C style cast in that test, it&amp;#39;s over 10 times slower.&amp;nbsp; That&amp;#39;s something to consider!&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;  So will I pick one over the other?&amp;nbsp; The answer is an emphatic &amp;quot;meh&amp;quot;.&amp;nbsp; In code I will probably use the &amp;quot;as&amp;quot; style.&amp;nbsp; When doing things in markup related to databinding it&amp;#39;s extremely useful to be able to use the C style cast and I will continue to do so.&lt;br /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38628" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us" length="75060" type="application/zip" /><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/IL/default.aspx">IL</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Casting/default.aspx">Casting</category></item></channel></rss>