In C# Enums can provide an easy way to limit values. Take an example where you have created a class with a property where you want to limit the values a user can have for that property. By creating a new
enum type, which declares a set of named constants, and then creating a new property (or field) derived from that type, you have control over those values.
Take a look at the following code for our class namespace Animals which has one class called Cat and one enum type called CatTypes:
using System;
namespace Animals {
public enum CatTypes {
ShortHair=1,
LongHair=2
}
public class Cat{
public static int Legs = 4;
public CatTypes CatType;
public String Meow(){
switch(System.Convert.ToInt32(CatType)){
case 1:
return "Meeeeoooowww! I am a ShortHair!";
break;
case 2:
return "Meeeeoooowww! I am a LongHair!";
break;
default:
return "Meeeeoooowww!";
break;
}
}
}
} |
The enum type CatTypes has two constants, ShortHair and LongHair, with the values 1 and 2.
We've then defined a property called CatType which is of the type CatTypes. This means that when a user is setting the value for CatType it must be one of the constants defined in the enum type CatTypes as follows:
<%@ Page Language="C#"%>
<%@ Assembly Src="animals.cs" %>
<%@ Import Namespace="Animals" %>
<script runat="server">
public void Page_Load(Object sender, EventArgs e){
Cat MyCat = new Cat();
MyCat.CatType=CatTypes.LongHair;
Response.Write("My cat has " +Cat.Legs+ " legs.<br/>");
Response.Write("My cat can say: "+MyCat.Meow()+"<br/>");
}
</script>
<html>
<body bgcolor="#FFFFFF">
</body>
</html>
|
When the page processes, the method Meow will return a string based on the CatType. If the user tries to put in a value like a string, or a constant not defined in the enum type CatTypes, this will produce an error. Using Enums is practical way to control values and is easy to implement within your programs.