1

If I am not wrong, when you use

(int)

it is the same than casting to Int32

Convert.ToInt32(value)

I was running a method with the following code:

 public int CurrentAge()
 {
      // return Convert.ToInt32((DateTime.Now - BirthDay).TotalDays)/365;
      return (int)((DateTime.Now - BirthDay).TotalDays)/365;
 }

Using this date:

  DateTime.ParseExact("13-07-1985", "dd-MM-yyyy",null)

And uncommenting the first line, the output is 30, but casting with (int) results in 29. Why is this behaviour?

Reading this post for example:

difference between Convert.ToInt32 and (int)

I understand it should be the same.

Community
  • 1
  • 1
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82

2 Answers2

5

You see the difference because the actual number is 29.5 or above. Casting truncates the value, while Convert performs rounding:

double x = 29.5;
Console.WriteLine("Cast: {0} Convert: {1}", (int)x, Convert.ToInt32(x));

This prints

Cast: 29 Convert: 30

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Looks like it has something to do with when you use to Convert.toInt32 you include the /365 but in the other one you don't.