Casting and Convert.ToInt32() behave different in C#?

270 Views Asked by At

Here a simple C# piece of code:

Convert.ToInt32(TimeSpan.FromMinutes(5).TotalMilliseconds);
//which brings me 300000

(int)TimeSpan.FromMinutes(5).Milliseconds;
//which brings me 0

Why would casting (int) result is different when compared to Convert.ToInt32()?

Shouldn't both bring the same result?

7

There are 7 best solutions below

1
On BEST ANSWER

In the first version you're using the TotalMilliseconds property - in the second you're using Milliseconds.

To give a simpler example, with no casting or calling to Convert.ToInt32:

TimeSpan ts = TimeSpan.FromHours(49);
Console.WriteLine(ts.Hours); // 1 (it's two days and one hour) 
Console.WriteLine(ts.TotalHours); // 49 (it's 49 hours in total)
0
On

The milliseconds is just the milliseconds PORTION of the 5 seconds. Use TotalMilliseconds on the second one as well.

0
On

Your error is that in the second example you are calling the .Milliseconds property, not the .TotalMilliseconds property.

The former returns 5 minutes in milliseconds. The latter returns the millisecond portion of 5 minutes, which is zero.

The cast vs. convert is a red herring!

0
On

In you first example you use TotalMilliseconds and then just Milliseconds.

0
On

You left out "Total" from the second line. So, this works.

(int)TimeSpan.FromMinutes(5).TotalMilliseconds;
0
On

They're the same... you've used TotalMilliseconds vs Milliseconds. The first is the total number of milliseconds in 5 minutes, whereas the second is the remainder, or the value which would be displayed if you wanted to display the time IE the '000' in '00:05:00.000'

0
On

The issue is not the conversion but that you are comparing TotalMilliseconds and Milliseconds!