I decided to write this tip/trick because my
question[
^] on the CodeProject's
questions[
^] forum lead to quite some different thoughts.
How do we convert objects to integers?
1 int convertedInteger;
2 object someValue;
3
4
5 Nullable<int> converted = someValue as Nullable<int>
6
7 int? converted = someValue as int?;
8
9 convertedInteger = (converted.HasValue) ? converted.Value : -1;
So for example, if you execute a Microsoft SQL Stored Procedure of which you are sure it returns an integer (or of course a
null
value), the best way is to use the returned value:
1 int storedProcedureResult = -1;
2
3 using (SqlCommand cmdMatch = new SqlCommand("spName", Connection))
4 {
5 cmdMatch.CommandType = System.Data.CommandType.StoredProcedure;
6 int? result = cmdMatch.ExecuteScalar() as int?;
7 storedProcedureResult = (result.HasValue) ? result.Value : -1;
8 }
Some improvements to the code above (thanks to
AspDotNetDev[
^] who added an alternate):
1 int storedProcedureResult = -1;
2
3 using (SqlCommand cmdMatch = new SqlCommand("spName", Connection))
4 {
5 cmdMatch.CommandType = System.Data.CommandType.StoredProcedure;
6 var converted = cmdMatch.ExecuteScalar() as int?;
7 int storedProcedureResult = converted ?? -1;
8 }
It may have been obvious to all you guys, but I struggled having to convert the returned
object first to a
string
in order to use
int.Parse()
and
int.TryParse()
:
1
2
3 int storedProcedureResult = -1;
4
5 using (SqlCommand cmdMatch = new SqlCommand("spName", Connection))
6 {
7
8 cmdMatch.CommandType = System.Data.CommandType.StoredProcedure;
9 object result = cmdMatch.ExecuteScalar();
10 if (result != null)
11 {
12 int.TryParse(result.ToString(), out storedProcedureResult);
13 }
14 }
Now we all know the neat way. ;)
I'm developing software for over two decades. I'm working as a cloud solution architect and a team lead at 4DotNet in The Netherlands.
In my current position, I love to help customers with their journey to the cloud. I like to create highly performant software and to help team members to a higher level of software development.
My focus is on the Microsoft development stack, mainly C# and the Microsoft Azure Cloud. I also have a strong affinity with Angular. As a result of my contributions to the community, I received the Microsoft MVP Award for Microsoft Azure.