C# Programming - Datatypes - Discussion

Discussion Forum : Datatypes - General Questions (Q.No. 15)
15.

Which of the following statement correctly assigns a value 33 to a variable c?

byte a = 11, b = 22, c;
c = (byte) (a + b);
c = (byte) a + (byte) b;
c = (int) a + (int) b;
c = (int)(a + b);
c = a + b;
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

Zoltán said:   4 years ago
By adding two-byte values, CLR assumes the sum may be bigger than a type of byte, so it declares the sum variable to int by default. And C is already declared to the type of byte, the explicit conversion is needed.
(1)

Abi said:   1 decade ago
Because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

Jiten said:   1 decade ago
For short and byte types compiler asks for explicit conversion.
The reason is its rule but with common sense that any mathematical calculations can go beyond byte and short types.

Ritesh said:   1 decade ago
Can any one have to explain this question in detail?

Jyothi said:   1 decade ago
Value type means int so why not type cast int. Please any one clarify my doubt?

Jatin said:   1 decade ago
This is an example of Type Promotion, viz: All byte and short are promoted to int.

The two correct expressions should be:

1. int c = a+b // If c wasn't declared byte.
2. c = (byte) (a+b) // The question asked.

Mekala said:   1 decade ago
Can any one explain this question in step by step?

Venu said:   6 years ago
byte a = 11, b = 22, c;

Here 'a' is declared as byte and 'b' is declared as byte then 'c' is also declared as a byte.
Then why do we need byte conversion for 'c'?

Zoltán said:   4 years ago
By adding two-byte values, CLR assumes the sum may be bigger than a type of byte, so it declares the sum variable to int by default. And C is already declared to the type of byte, the explicit conversion is needed.

Post your comments here:

Your comments will be displayed after verification.