C# Programming - Control Instructions - Discussion

Discussion :: Control Instructions - General Questions (Q.No.7)

7. 

What will be the output of the C#.NET code snippet given below?

char ch = Convert.ToChar ('a' | 'b' | 'c'); 
switch (ch)
{
    case 'A': 
    case 'a':
    Console.WriteLine ("case A | case a");
    break;
    
    case 'B': 
    case 'b':
    Console.WriteLine ("case B | case b");
    break;
    
    case 'C':
    case 'c':
    case 'D':
    case 'd':
    Console.WriteLine ("case D | case d");
    break;
}

[A]. case A | case a
[B]. case B | case b
[C]. case D | case d
[D]. Compile Error
[E]. No output

Answer: Option C

Explanation:

No answer description available for this question.

Rachna said: (Jul 4, 2011)  
How this is solved?

Shylender said: (Nov 8, 2011)  
Can anyone explain it. I didn't understand.

Yelani said: (Apr 5, 2012)  
I do not understand how the variable ch takes the value 'c'. Can somebody explain this please?
Thanks

Rathi said: (Jun 27, 2012)  
ASCII value of each char are,

'a' --> 0110 0001
'b' --> 0110 0010 (| - Bit wise OR)
'c' --> 0110 0011
-----------------
'a'|'b'|'c' --> 0110 0011 (it nothing but 'c')

In case c is true, then there is no Break after c, So it execute continuously

Therefore output is : [c]. case D | case d

Ashwini Shelke said: (Dec 21, 2013)  
The trick behind this question is it first will convert a character to its bit value and performs or operation and final result of or operation will be returned as a char.

Ex. convert.ToChar('0'|'1')

Here 0 will get its bit value as 000 and 1 as 001 and or result of these two ll be 1 so it will return 1. If it is & operation then it will return 0.

Venkat said: (Feb 14, 2014)  
I Can't able to understand it. Then why compiler not assign a / b to character 'ch' variable. I think left to right precedence base last 'c' is assign to 'ch' variable. Please clear my doubt's.

Shankar Jat said: (Aug 18, 2014)  
0 and 1 return in case of ||(OR) , not in case of |....
'a' --> 0110 0001
'b' --> 0110 0010
'c' --> 0110 0011
'a'|'b' ---> 01100011
('a'|'b')|'c' --> 01100011('c')
-----------------
So,

'a'|'b'|'c' --> 0110 0011
Thats why it return 'c'.

And match with 'c' after that there is break statement till got break....so o/p is case D | case d.

Rajveer Singh said: (Oct 22, 2014)  
First ch is assigned value 'a' then 'b' and at last 'c' because of the 'or', '|' operator, so what ever be the last value, will be assigned to c.

Sushant said: (Oct 11, 2015)  
Can you tell me properly how it is working? Because how you decided to convert to ASCII value?

Pathan said: (Oct 10, 2016)  
How can we find ASCII value?

Mayank Kumar said: (Apr 19, 2017)  
Pleas e solve this Query .
What will be output. I can not understand logic.

char ch = Convert.ToChar('a' | 'B' | 'C'|'D' );

Sridhar said: (Jun 9, 2018)  
How? tell me.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.