Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the C# compiler to emit an error if a switch(enum_val) is missing a case statement?

Tags:

I just realized I added a value to the list of "must-handle" values in my enum, but I didn't catch it until runtime. I know the C# compiler is really powerful when it comes to reflection and introspection of types, so I was wondering if there was a way to force a switch/case statement to cover all possible enum values?

Example:

enum Colors {    Red,    Blue,    Green,    Yellow };  Colors c = ...;  switch (c) {    case Colors.Red:  // No error, Red is a Color       break;    case Colors.Blue:    case Colors.Green:  // No error, Blue and Green handled as well       break; }  // whoops! "error: 'Colors.Yellow' unhandled"    // or even, "error: no 'default' and 'Colors.Yellow' unhandled" 

I want a compile-time solution.

like image 616
moswald Avatar asked May 09 '11 04:05

moswald


People also ask

Does a C+ exist?

C+ (grade), an academic grade. C++, a programming language. C with Classes, predecessor to the C++ programming language.

Is C easy to learn?

While C is one of the more difficult languages to learn, it's still an excellent first language pick up because almost all programming languages are implemented in it. This means that once you learn C, it'll be simple to learn more languages like C++ and C#.

How to get your c file fast?

How to Get Your C File Fast Step #2: Fill-out the form, paying close attention to Sections I, III, V, and VI. In Section III, Records You Are Seeking, click the radio button for “Claims File (C-File.” You can click multiple radio buttons if you’d like any additional documents and records.

What is the easiest version of C on guitar?

NOTE: As with all versions of C, you should aim to not play the 6th string. This is the easiest possible version of the C guitar chord. It’s simple to play and is ideal for children (with their smaller hands). It’s also good for adults who are struggling or just starting out with guitar.

Is it hard to play C on guitar?

This is hard in the early days of learning guitar as you don’t have the necessary amount of dexterity, flexibility or strength in your fingers yet. But don’t worry, thankfully there are some much easier versions of the C guitar chord that you can play that still sound good and will act as ‘stepping stones’ for you in learning the full version of C.

How do I learn C major 7 on guitar?

Learning to play C Major 7, with fingers 2 and 3, is the ideal stepping stone for you to use in learning to play a full C guitar chord. ✓ Stop struggling.


1 Answers

You can use SwitchEnumAnalyzer to get compiler-time warnings of this kind. I just used it in my project and it works nicely. As in any Roslyn analyzer, you can choose level of notification - if it should be just warning, or a proper error.

like image 81
Lukáš Lánský Avatar answered Sep 20 '22 22:09

Lukáš Lánský