Junior Mayhe
Junior Mayhe

Reputation: 16401

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

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?

Upvotes: 0

Views: 274

Answers (7)

Dion Pooran
Dion Pooran

Reputation: 31

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

Upvotes: 1

CWilliams
CWilliams

Reputation: 213

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'

Upvotes: 1

John Fisher
John Fisher

Reputation: 22721

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

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

Upvotes: 1

Remy
Remy

Reputation: 12693

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

Upvotes: 2

Rob Levine
Rob Levine

Reputation: 41298

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!

Upvotes: 1

Jared Peless
Jared Peless

Reputation: 1120

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499770

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)

Upvotes: 8

Related Questions