Wednesday, April 6, 2016

Enum in c# with Example?



An Enum is user defined value data type. Enum is a group of related constant. The enum keyword is used to declare enumeration.Enums types can be float, int, byte, double etc.

The example of the enums is given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication12
{
    public enum operation
    {
        sum,sub
    }
    class Class1
    {
        public int calculate(int i, int j,operation o)
        {
            if (o == operation.sum)
            {
                return i + j;
            }
            else if (o == operation.sub)
            {
                return i - j;
            }
            return 0;
        }
    }
}

.cs code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
           int x= obj.calculate(10, 5, operation.sum);
           int y = obj.calculate(10, 5, operation.sub);
           MessageBox.Show(x.ToString());
           MessageBox.Show(y.ToString());
        }
    }
}
 
Output: 
15

 

No comments:

Post a Comment