Labels

Tuesday, May 6, 2008

Check before converting String

Hi,

Before making a Convert Funtion, recommended is to check – Can they be converted?

Here is approach to be taken:

Converting String to Integer:

string str = "ABC";

int i;

bool res = Int32.TryParse(str, out i);

if (res)

{

i = Convert.ToInt32(str);

}

Converting String to Decimal:

string str = "ABC";

decimal i;

bool res = Decimal.TryParse(str, out i);

if (res)

{

i = Convert.ToInt32(str);

}

Thanks & Regards,

Arun Manglick || Tech Lead

2 comments:

  1. Hi Arun,

    In your code below:

    bool res = Int32.TryParse(str, out i);

    if (res)

    {

    i = Convert.ToInt32(str);

    }

    There is no need to again Convert str into Int32 as of TryParse method returns the converted 32 bit integer value if conversion is successful else returns zero.

    ..Paresh

    ReplyDelete
  2. Thanks Paresh for the valuable input.

    ReplyDelete