Conversions and checked arithmetic
A conversion represents a value in another type. Some conversions are implicit; others require a cast. Converting a wide integer to a smaller integer may lose information. Choose an explicit overflow policy and distinguish numeric conversion from parsing text.
long wide = 120;int count = checked((int)wide);long expanded = count;System.Console.WriteLine(expanded);System.Console.WriteLine((int)3.9);System.Console.WriteLine(System.Convert.ToInt32(3.9));The bounded narrowing succeeds; the cast truncates while Convert rounds.
Expected output (reasoned, not executed):
12034Implicit conversions and casts
An int can be assigned to long without a cast. A long variable generally requires an explicit (int) cast to become int. Not all implicit numeric conversions preserve exact precision (for example long to double). Casting an in-range fractional number to int truncates toward zero. System.Convert.ToInt32(double) instead rounds to the nearest integer, using the even integer at an exact midpoint.
Handle out-of-range values
checked((int)wide) throws System.OverflowException for an out-of-range long. For integral narrowing, unchecked keeps the low bits. The checked context also affects selected integral arithmetic operations; it is not a universal exception guard. A constant overflow is ordinarily a compile-time error unless explicitly unchecked; use nonconstant operands for runtime examples. Integer divide-by-zero still fails. Catch syntax is previewed here only to show the expected error; later error-handling material develop it further.
Parse text rather than casting it
int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) returns a success flag and assigns an int result. out means the method writes to that variable; method parameters are covered later. The integer style accepts leading/trailing whitespace and a leading sign but not decimal fractions. Parse can throw for invalid or out-of-range text. Check the success flag before using value. Parsing does not establish a business-valid range.
Examples and walkthroughs
long wide = 2147483648L;System.Console.WriteLine(unchecked((int)wide));try{ System.Console.WriteLine(checked((int)wide));}catch (System.OverflowException){ System.Console.WriteLine("Out of range");}The same source value has two different overflow policies. The catch block handles only the expected overflow exception.
Expected output (reasoned, not executed):
-2147483648Out of rangeusing System.Globalization;bool ok = int.TryParse("42", NumberStyles.Integer, CultureInfo.InvariantCulture, out int count);System.Console.WriteLine(ok);System.Console.WriteLine(count);bool bad = int.TryParse("4.2", NumberStyles.Integer, CultureInfo.InvariantCulture, out int ignored);System.Console.WriteLine(bad);The using directive makes globalization type names available. Only the integer text parses successfully; ignore the output when parsing fails.
Expected output (reasoned, not executed):
True42FalseCommon mistake and correction
Do not cast a string with (int)text; it is not a numeric operand. Do not rely on unchecked narrowing to validate a count or on a successful parse to enforce nonnegative values.
Try it yourself
Convert long 250 to int with checked. Compare casting 2.5 to int with Convert.ToInt32(2.5) and Convert.ToInt32(3.5). Parse "-3" and decide whether it is a valid inventory count.
Next: Null-aware and conditional operators. These examples target C# 14 / net10.0 and are static study material; compiler and ByteMind execution have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Conversions and checked arithmetic — knowledge check
Apply the lesson concepts to the following scenarios.
Which conversion is implicit for variables?
What is (int)(-3.9)?
What does checked((int)wide) do for long wide = 2147483648L?
What is Convert.ToInt32(3.5)?
TryParse succeeds on "-3". What still needs checking for inventory?