Should I just always Convert.ToInt32 my integers to account for potential nullable integers?
Posted
by
Rowan Freeman
on Programmers
See other posts from Programmers
or by Rowan Freeman
Published on 2013-10-22T04:59:01Z
Indexed on
2013/10/22
10:13 UTC
Read the original article
Hit count: 273
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?
© Programmers or respective owner