TryParse and Nullable Types

RadicalWacko January 29th, 2009

I just ran into an irritating little problem with using TryParse when assigning to nullable object.  The following is the code I was using to assign a value from a ASP.NET dropdown list to a nullable Int32 variable:

If Int32.TryParse(ddlExample.SelectedValue, testobj.TestNullableInt32 )Then
     testobj.TestDescription = ddlExample.SelectedItem.Text
End If

 

Apparently, TryParse actually attempts to access the value of the object to which it attempts to assign the parsed value which can cause an InvalidOperationException when it attempts to retrieve the value of the nullable object.  So make sure to assign the parsed value to a regular type before assigning it to a nullable object.  Oh yeah, I know it’s VB.NET code, but I do what the client wants. ;)

2 Responses to “TryParse and Nullable Types”

  1. John dauphineon 31 Oct 2009 at 2:03 am

    I found a couple of code posting on a nullable tryparse method.  The code the I came up with is here johndauphine.blogspot.com/…/nullable-tryparse-function-in-c.html.

  2. John Davidsonon 24 Jan 2010 at 6:22 pm

    I have created a Generic Parse routine in Visual Basic for .Net 3.5 at

    http://ods.dyndns.org/FlexWiki/default.aspx/OdsWiki/GenericParseInVisualBasic.html

    The included unit tests show how to call the extension method.

Trackback URI | Comments RSS

Leave a Reply