Search code examples
c#castingtype-conversionnumeric-conversion

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?


Solution

  • 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)