Given the declarations below, which statement correctly assigns the value 33 to variable c in C#? byte a = 11, b = 22, c;

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:

  • a and b are bytes with values 11 and 22.
  • We need c (also a byte) to become 33.
  • Arithmetic on bytes promotes operands to int.


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:

Compute a + b → promoted to int with value 33.Cast the result back to byte: (byte)(a + b).Assign to c.


Verification / Alternative check:
Attempt to compile each option: only c = (byte)(a + b); compiles cleanly and yields 33.



Why Other Options Are Wrong:

  • B: (byte)a + (byte)b still promotes to int; missing final cast to byte.
  • C/D: Casts to int produce an int result; cannot assign to byte without another cast.
  • E: Implicit narrowing conversion is not allowed; compile-time error.


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

No comments yet. Be the first to comment!
Join Discussion