Enum
An enumerated type is declared using the enum
keyword.
By default, the enumerator values are 0,1,2 …etc
Enums
have these benefits:
- Enum variable only allow permitted values that it can take and restrict the others. (i.e anything which is not a day cannot be added to the above example)
- They force a programmer to think about all the possible values that the enum can take.
- They increase readability of the source code.
You can use extension methods to add
functionality specific to a particular enum type.
Copy and run this program in Windows Form
Application
Days
enumeration represents the possible days in a week. An extension method named weekEnd is added to the Days
type so that each instance of that type now "knows"
whether the day is a week end or not.
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EnumExtension
{
//
Define an extension method in a non-nested static class.
public static class Extensions
{
public static Days weekendDay1 = Days.Sun;
public static Days weekendDay2 = Days.Sat;
public static bool weekEnd(this Days day)
{
if (day == weekendDay1 || day == weekendDay2)
return true;
else
return false;
}
}
public enum Days { Sat = 0, Sun = 1, Mon = 2, Tue = 3, Wed = 4, Thurs = 5,
Fri = 6 };
class EnumExtension
{
static void Main(string[] args)
{
Days day1 = Days.Mon;
Days day2 = Days.Sun;
Console.WriteLine("\r\nFinding
if the day is a week end!\r\n");
Console.WriteLine("Day1 {0} a
week end.", day1.weekEnd() ? "is" : "is not");
Console.WriteLine("Day2 {0} a
week end.", day2.weekEnd() ? "is" : "is not");
}
}
}
No comments:
Post a Comment