Skip to main content
GameDev.net gamedev.net
🔒 Locked

switch statements

Started by popcorn Sep 5, 2007 at 9:52 PM 2 replies 1.4k views
Original Post
popcorn
popcorn
Why is the following not allowed in C#:

            string dice;

            switch (type)
            {
                case Class.Barbarian:
                case Class.Bard:
                    dice = "4d4";
                    break;
                case Class.Cleric:
                case Class.Rogue:
                    dice = "5d4";
                    break;
                case Class.Druid:
                    dice = "2d4";
                    break;
                case Class.Fighter:
                case Class.Paladin:
                case Class.Ranger:
                    dice = "6d4";
                    break;
                case Class.Monk:
                    dice = "5d4";
                    break;
                case Class.Sorcerer:
                case Class.Wizard:
                    dice = "3d4";
                    break;
            }


The compiler says dice is unassigned and you cannot use dice as a result later on. Is there any way round this?
How about them apples?
Sneftel
Sneftel
The compiler isn't quite smart enough to determine that one of the case statements will always be true. Put in a default clause, which throws an exception.
popcorn
popcorn
Thanks putting in the default clause fixes the problem. Out of curiosity why is the compiler not smart enough to work out that one of the default cases is always true?
How about them apples?
Telastyn
Telastyn
Quote:
Original post by popcorn
Thanks putting in the default clause fixes the problem. Out of curiosity why is the compiler not smart enough to work out that one of the default cases is always true?


Because it's technically not always true. Assume this is how type is assigned:
type = (Class)900000;   // or some other number not equivalent to your enum.


type is then a valid instance of Class, but not triggered by any of your cases. Though even if you cover all the instances it still won't figure it out. There's probably some construct which makes such determination imprecise.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.