Why does my switch work when it has single quotes?

So disclaimer, I am pretty new to C# and trying to learn the finer intricacies. I have a classwork assignment that I coded and it works, but I'm not sure why it works, and want to understand it.

Here is the code, Its not the full code, i just cut out the relevant parts:

    int studentType = 0;
    switch (studentType)
    {
        case 1:
            studentType = '1';
            WriteLine("What is your GPA?");
            gpa = Convert.ToDouble(ReadLine());
            break;

        case 2:
            studentType = '2';
            WriteLine("What is the title of your thesis?");
            thesis = ReadLine();
            break;

        case 3:
            studentType = '3';
            WriteLine("What is the title of your dissertation?");
            dissertation = ReadLine();
            break;

        case 4:
            break;

        default:
            WriteLine("Invalid option input.");
            break;
    }//Switch for student Type

As noted, the case command works perfectly fine like this. What I accidently did was initially put case 'x': and that ended up not working, so i deleted all the single quotes.

Here is the 2nd part, and why I am confused:

    switch (studentType)
    {
        case '1':
        case '4':
            WriteLine($"GPA: {gpa:f2}");
            break;

        case '3':
            WriteLine($"Dissertation title: {dissertation}");
            break;

        case '2':
            WriteLine($"Thesis title: {thesis}");
            break;
    }//end of studentType switch

So originally I tried writing the case without the single quotes, but every time I ran 1, GPA never populated, so I tried to put in the single quotes, and it works, but I'm not sure why.

Since studentType is an integer, it would make sense for the first switch to be without single quotes, but how is the switch requiring single quotes?

I guess I can submit it as is as long as it works correctly, but I mainly want to understand whats going on.

Thanks for the help!

Jon Skeet
people
quotationmark

There's an implicit conversion from char to int, and a constant char expression can be used as a constant int expression, which is what you've got. The value of the int is the UTF-16 code unit associated with the char.

Here's another example of that:

const int X = 'x';

That's also why your assignment statements worked:

studentType = '1';

So this:

int value = ...;
switch (value)
{
    case '1':
        // ...
        break;
}

is equivalent to:

int value = ...;
switch (value)
{
    case 49:
        // ...
        break;
}

... because 49 is the UTF-16 code point associated with the character '1'.

people

See more on this question at Stackoverflow