What is a NullReferenceException, and how do I fix it?
See the question and my original answer on StackOverflowAnother scenario is when you cast a null object into a value type. For example, the code below:
object o = null;
DateTime d = (DateTime)o;
It will throw a NullReferenceException
on the cast. It seems quite obvious in the above sample, but this can happen in more "late-binding" intricate scenarios where the null object has been returned from some code you don't own, and the cast is for example generated by some automatic system.
One example of this is this simple ASP.NET binding fragment with the Calendar control:
<asp:Calendar runat="server" SelectedDate="<%#Bind("Something")%>" />
Here, SelectedDate
is in fact a property - of DateTime
type - of the Calendar
Web Control type, and the binding could perfectly return something null. The implicit ASP.NET Generator will create a piece of code that will be equivalent to the cast code above. And this will raise a NullReferenceException
that is quite difficult to spot, because it lies in ASP.NET generated code which compiles fine...