Enumeration and Switch Case

enum c# vb.net

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.

Syntax:

enum 
{
	enum list
};

Switch Case

C# switch case vb.net

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

C#

public enum backColors
{
	RED, BLUE, GREEN, YELLOW
}

VB.Net

Public Enum backColors
	RED
	BLUE
	GREEN
	YELLOW
End Enum
C# enumaration vb.net

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

C# Source Code

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);
        }
    }
}

VB.Net Source Code

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