Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Convert.ToInt vs (int)

Tags:

c#

types

I noticed in another post, someone had done something like:

double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));

Why did they use the convert function, rather than:

double d = 3.1415;
int i = (int)d;

which has an implicit floor and convert.

Also, more concerning, I noticed in some production code I was reading:

double d = 3.1415;
float f = Convert.ToSingle(d);

Is that the same as:

float f = (float)d;

Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.

like image 762
Wyzfen Avatar asked Sep 19 '08 17:09

Wyzfen


People also ask

Which is better int Parse or convert ToInt32?

Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.

What is the difference between int TryParse () & Convert ToInt32 () in C#?

The difference is this: Int32. Parse() and Int32. TryParse() can only convert strings.

What is the difference between convert ToInt32 and convert toint64?

Thus int32 would be limited to a value between (-256^4/2) and (256^4/2-1). And int64 would be limited to a value between (-256^8/2) and (256^8/2-1).

Why convert ToInt32 is used in C#?

ToInt32(String, IFormatProvider) Method. This method is used to converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information.


1 Answers

Casting to int is implicit truncation, not implicit flooring:

double d = -3.14;
int i = (int)d;
// i == -3

I choose Math.Floor or Math.Round to make my intentions more explicit.

like image 94
Michael L Perry Avatar answered Oct 12 '22 13:10

Michael L Perry