Vincent Ning
Vincent Ning

Reputation: 25

What is the `(int)` after `return` means

  public static int SumDigits(int number)
  {
     return (int)number.ToString().Sum(x => char.IsNumber(x) ? char.GetNumericValue(x) : 0);
  }

What is the (int) after return means.

Its perfectly running, just need to understand it, thanks.

Upvotes: 0

Views: 48

Answers (1)

Dmitry S.
Dmitry S.

Reputation: 8503

The GetNumericValue method returns a double. The (int) is a cast that converts the returned double to int.

https://learn.microsoft.com/en-us/dotnet/api/system.char.getnumericvalue?view=netcore-3.1#System_Char_GetNumericValue_System_Char_

Keep in mind that it truncates the decimal part which should be okay for numeric char values. There are methods like Convert.ToInt32(doubleValue) or (int) Math.Round(doubleValue) that round the result instead of truncating it.

Upvotes: 3

Related Questions