Monday, September 22, 2008

Enumeration in Asp.net


How to get Enum values:


First of all i will tell you what is Enum in asp.net?


An Enum is a named constant whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values.



Class Enum is derived from class ValueType; that is, Enum is itself a reference type, not a value type.



Enum provides methods to compare instances of this class, convert the value of an instance to its string representation, convert the string representation of a number to an instance of this class, and create an instance of a specified enumeration and value.



How to declare Enum?


// Declare the Enumeration


public enum MessageSize {


Small = 0,


Medium = 1,


Large = 2


}


// Create a Field or Property


public MessageSize msgsize;


// Assign to the property using the Enumeration values


msgsize = Small;



How to Use Enum Using MemberInfo?


do remember to include System.Reflection;


Here is the Example to get the enum values through memberInfo :


MemberInfo[] memberInfos = typeof(MessageSize).GetMembers(BindingFlags.Public | BindingFlags.Static);



for (int i = 0; i < memberInfos.Length; i++)


{


ddProperty.Items.Add(new ListItem(memberInfos[i].Name, memberInfos[i].GetType().Name));


}


in the above example i m adding the Values of enum to a DropDown list-ddlProperty.


i hope its enough to get the values of enum using MemberInfo(Thanks to Reflection)


No comments: