code to add two no in c# with robust way

Posted by Sahoo under C# on 5/29/2012 | Points: 10 | Views : 2050 | Status : [Member] | Replies : 3
Hi

How to add two no in c #. User can input anything of his/her wish ,they can be int, float,double,string,special character .So we have to handle all cases with one robust code.
And it can be 32 or 64 bit also.




Responses

Posted by: Fool2code on: 5/29/2012 [Member] Starter | Points: 25

Up
0
Down
There could be better ways but I think it is pretty difficult to get the data type of value entered than do some action on it , some sample code.

protected void btnSave_Click(object sender, EventArgs e)

{
int cases = ParseString(Convert.ToString(txtFirst.Text));
int second = ParseString(Convert.ToString(txtSecond.Text));
cases = second == cases ? cases : 0;
string finalValue = AddValues(Convert.ToString(txtFirst.Text), Convert.ToString(txtSecond.Text),cases);
}

private int ParseString(string str)
{
Int32 intValue;
Int64 bigintValue;
decimal doubleValue;
char charValue;

// Place checks higher in if-else statement to give higher priority to type.

if (Int32.TryParse(str, out intValue))
return 1;
else if (Int64.TryParse(str, out bigintValue))
return 2;
else if (decimal.TryParse(str, out doubleValue))
return 3;
else if (Char.TryParse(str, out charValue))
return 5;
else return 0;

}


private string AddValues(string first, string second, int Cases)
{
string values = string.Empty;
switch (Cases)
{
case 1:// for int
values = (Convert.ToInt16(first) + Convert.ToInt16(second)).ToString();
break;
case 2:// for long
values = (Convert.ToInt64(first) + Convert.ToInt64(second)).ToString();
break;
case 3://for float
values = (Convert.ToDouble(first) + Convert.ToDouble(second)).ToString();
break;
case 4:// for char
values = (Convert.ToChar(first) + Convert.ToChar(second)).ToString();
break;
default:
values = first + second;
break;
}

return values;
}


Sahoo, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sakthi.Singaravel on: 5/29/2012 [Member] Silver | Points: 25

Up
0
Down
nice code..
Thank you..

Regards,
Singaravel M

Sahoo, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 5/31/2012 [Member] Bronze | Points: 25

Up
0
Down
Fool2code

good


Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Sahoo, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response