Should I just always Convert.ToInt32 my integers to account for potential nullable integers?
- by Rowan Freeman
If my MSSQL database contains a data type that is NULL (i.e. null is allowed) then ORMs, such as EntityFramework in my case, create .NET objects that are nullable.
This is great, and the way I use nullables is like this:
C#
int? someInt = 5;
int newInt = someInt.Value; // woot
VB.NET
Dim someInt As Integer?
Dim newInt As Integer = someInt.Value ' hooray
However, recently I had to make a change to the database to make an Id field no longer NULL (nullable). This means that .Value is now broken. This is a nuisance if the Id property is used a lot.
One solution that I thought of is to just use Convert.ToInt32 on Id fields so it doesn't matter if an int is nullable or not.
C#
int newInt = Convert.ToInt32(someInt); // always compiles
VB.NET
Dim newInt As Integer = Convert.ToInt32(someInt) ' always compiles
Is this a bad approach and are there any alternatives?