C#.NET — Data type rules: choose the correct set of statements. Assigning an integer literal to a byte variable that exceeds byte range causes a compilation error. Non-literal numeric types of larger storage size cannot be implicitly converted to byte. Byte cannot be implicitly converted to float. A char can be implicitly converted only to int. We can cast integral character codes explicitly.

Difficulty: Easy

Correct Answer: 1, 2, 5

Explanation:


Introduction / Context:
This question checks your knowledge of implicit and explicit numeric conversions in C#, especially narrowing versus widening conversions and how literals are treated.



Given Data / Assumptions:

  • Literals may undergo constant-expression checks for range when assigned to smaller types.
  • Narrowing conversions from variables of larger types are not implicit.
  • Widening conversions (e.g., byte to float) are implicit.


Concept / Approach:
Rule of thumb: If the target type can represent all values of the source type, the conversion may be implicit (widening). Otherwise, an explicit cast is needed (narrowing). The compiler also performs constant-expression checks for literals.



Step-by-Step Solution:

(1) True: Assigning, e.g., byte b = 300; fails at compile time because 300 is out of byte range. (2) True: Implicitly converting an int variable to byte is illegal; requires an explicit cast. (3) False: byte → float is a widening conversion and is implicit. (4) False: char has implicit conversions to several numeric types (ushort, int, uint, long, ulong, float, double, decimal), not only int. (5) True: You can explicitly cast integral character codes to char and vice versa where appropriate.


Verification / Alternative check:
Compile small snippets demonstrating byte b = 3.14f; (error) vs float f = (byte)200; (works with cast) vs float f2 = (byte)10; (implicit allowed as widening).



Why Other Options Are Wrong:
Any set including (3) or (4) is incorrect due to misunderstanding widening rules and char conversions.



Common Pitfalls:
Assuming all numeric types interconvert implicitly; ignoring constant-expression range checks for literals.



Final Answer:
1, 2, 5

More Questions from Datatypes

Discussion & Comments

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