Wednesday, March 14, 2007

surprise: int.TryParse(xx,yy)

I really get surprised about the following behaviour:

when I've tried to use the follwoing line of code:

if(!int.TryParse(row["myRowName"] as string, out myDefinedInt))

tryParse always returned me false and I assinged a default value. After making sure that all my rows have values for myRowName I were confused.

a friend suggested to use row["myRowName"].ToString() and voila it worked like i wanted.

I didn't really figured out why that happens, then in none of my cases the value were empty that my expression as string would return null.

here a bit more code:

DataSet data = DataReader.GetData();
DataTable tab = data.Tables["MyTableName"];
DataView view = tab.DefaultView;

view.RowFilter = "RowNameA LIKE '%" + valA + "%' AND RowNameB LIKE '%" + valB + "%'";

if (view.Count > 0)
Data.MyDataObject item;
foreach (DataRowView row in view)
item = new Data.MyDataObject();
item.SomeValue1 = row["SomeValue1"] as string;
item.SomeValue2 = row["SomeValue2"] as string;
int outData = -1;
if (!int.TryParse(row["SomeValue3"].ToString(), out outData))
item.SomeValue3 = 40;
item.SomeValue3 = outData;

etc ... etc ... etc ...

Thanks to richi (Y)

1 comment:

Anonymous said...

"As String" is not equivalent with ".ToString()" the first is a type cast and the later a method call which in some cases is a typecast other cases just returns the class name as a string depending on the class implementation.

if 'row["myRowName"] as string' casues an exception your TryParse will fail regardless of what row["myRowItem"] contains.

I personally never use the 'As' keyword/notation unless no other solution is available. However it is commenly used by Visual Basic developers.

I use '(string)object' or 'object.ToString()' or the 'System.Convert' static class.

Hope it helps :-)

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: Its free and easy to use, we provide all sources at codeplex.

Facebook Badge