Difficulty: Easy
Correct Answer: c = (byte) (a + b);
Explanation:
Introduction / Context:
C# applies integral promotion rules to arithmetic with small integer types (byte, sbyte, short). Understanding these rules is crucial to avoid compilation errors and unintended results.
Given Data / Assumptions:
Concept / Approach:
In C#, expressions like a + b where a and b are bytes are evaluated as ints. Assigning the int result back to a byte requires an explicit cast after the addition. Casting operands individually does not help because the addition result is still promoted to int; the cast must be applied to the entire sum.
Step-by-Step Solution:
Verification / Alternative check:
Attempt to compile each option: only c = (byte)(a + b); compiles cleanly and yields 33.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming per-operand casts prevent result promotion; in C#, the operator result type controls assignment requirements.
Final Answer:
c = (byte) (a + b);
Discussion & Comments