Using a Switch statement with Enum

Enumeration and Switch Case

enum c#

Enums are strongly typed constants and very useful in programming when your program needs constant values. It provides efficient way to assign multiple constant integral values to a single variable.

enum <name> { enum list };

Switch Case

C# switch case

Switch...Case can act upon enum values. The following C# program shows how to Enum work with In the following program , declare an enum backColors.

public enum backColors { RED, BLUE, GREEN, YELLOW }
Public Enum backColors RED BLUE GREEN YELLOW End Enum
C# enumaration

In the paintColor color method , pass enum values and color the background of the form with the help of a statement.

Source Code | C#
using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public enum backColors { RED, BLUE, GREEN, YELLOW } public void paintColor(backColors pc) { switch (pc) { case backColors.RED: this.BackColor = Color.Red ; break; case backColors.BLUE: this.BackColor = Color.Blue ; break; case backColors.GREEN: this.BackColor = Color.Green ; break; case backColors.YELLOW: this.BackColor = Color.Yellow ; break; default: this.BackColor = Color.Gray ; break; } } private void button1_Click(object sender, EventArgs e) { paintColor(backColors.GREEN); } } }
Source Code | Vb.Net
Public Class Form1 Public Enum backColors RED BLUE GREEN YELLOW End Enum Public Sub paintColor(ByVal pc As backColors) Select Case pc Case backColors.RED Me.BackColor = Color.Red Exit Select Case backColors.BLUE Me.BackColor = Color.Blue Exit Select Case backColors.GREEN Me.BackColor = Color.Green Exit Select Case backColors.YELLOW Me.BackColor = Color.Yellow Exit Select Case Else Me.BackColor = Color.Gray Exit Select End Select End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click paintColor(backColors.GREEN) End Sub End Class

NEXT.....Passing Data