2
Answers

Having a weird problem with Object.ToString()

Peter

Peter

15y
3.5k
1
Consider the following snipit of code:
 			string sql = "SELECT COUNT(*) FROM member WHERE member_no = 35000";

object resObj = dba.GetScalarFromDB(sql);
string res = dba.GetScalarFromDB(sql).ToString();

int count = 0;

if (int.TryParse(res, out count))
Console.WriteLine("Count = " + count.ToString());
else
Console.WriteLine("Error ocurred while converting");

dba is a custom class that handles database queries.  The GetScalarFromDB(string SQL) does Command.ExecuteScalar() and returns whatever comes back boxed as an object.

The weird thing is that the above code evaluates differently on 2 different PCs:

on my PC the results are as follows:
 resObj = {1M} {decimal}
res = "1" {string}
tryParse = true;
count = 1 {int}

On my coworker's PC the results are (bold are the differences):
 resObj = {1M} {decimal}
res = "1.0" {string}
tryParse = false;
count = 0 {int}

By examining the cause of tryParce failure I figured out that the exception is "Input string is not in a correct format"

I've been racking my brain trying to solve the reason for the difference and can't.

Does anyone have any clue as to why there is a difference?
 
Answers (2)
0
Peter

Peter

NA 4 0 15y
That much I know.  My question is, why one PC converts 1 to string and gets "1" and the other does the same thing and gets "1.0"?
0
Manish Dwivedi

Manish Dwivedi

NA 8.3k 1.2m 15y
Hi

This is happening due to this res = "1.0" {string} while converting.

because you are using int.TryParse so u have to pass the values like 1,2,123,10 etc in the res parameter.

I think u got it.