Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in Converting Decimal To String in C#.Net

While Converting Decimal to String, I tried two methods.

Method 1:

    string a = "100.00", b = "50.00";
    string Total = (string)(Convert.ToDecimal(a) + Convert.ToDecimal(b));

It throws error, cannot convert Decimal to String.

Method 2:

    string Total = (Convert.ToDecimal(a) + Convert.ToDecimal(b)).ToString();

It doesn't throw error and it is working fine.

I want to know the difference between these two methods of Conversion and Why it throws error when I used Method 1?

like image 773
thevan Avatar asked Dec 06 '22 21:12

thevan


2 Answers

The first method is trying to take a decimal (the result of adding the 2 decimals) and cast it as a string. Since there's no (implicit or) explicit conversion from decimal to string, it throws because of the mismatch.

The second one takes a decimal and calls a ToString() method on it - since ToString is a valid method on the decimal type, this makes a normal instance method call and you get the return value of that call, which is a string.

Since you're using Convert calls already, you might find it more natural to do Convert.ToString to get the decimal back to a string.

It might be more clear if you separate the 'add two decimals' to a separate local var, since that's common to both here.

So, the (commented out) total1 fails because it's trying to just cast, and we have no conversion available to do so. The latter two both work fine, since they are method calls that are returning a string.

string a = "100.00", b = "50.00";
decimal result = Convert.ToDecimal(a) + Convert.ToDecimal(b);
//string total1 = (string)result;
string total2 = result.ToString();
string total3 = Convert.ToString(result);
like image 183
James Manning Avatar answered Dec 09 '22 10:12

James Manning


The first code tries to "type cast" a decimal to string, where as the second one calls the ToString method on decimal to get the string representation of decimal. Type casting from decimal to string won't work, unless decimal type overloads the type conversion operator which it doesn't and hence the type casting throws exception.

Type casting in this case is like asking the CLR system to type cast a decimal to string, which CLR is unable to do because it doesn't find a way to do it. Calling ToString is asking the decimal type to returns its string representation

like image 23
Ankur Avatar answered Dec 09 '22 09:12

Ankur