Constants

You can declare constant values by adding CodeMemberField objects to the CodeTypeDeclaration that represents the class. These are class-level constants. Rather than add them individually, you can pass a generic List<string> to the AddConstant() method and iterate the members. Listing 1-16 shows how this is done.

Listing 1-16. Adding Constants

List<string> oList = new List<string>();

oList.Add("Car"); oList.Add("Bus"); oList.Add("Limo"); oList.Add("Tank");

public void AddConstants(List<string> oConstant) {

//Iterate through the generic list. Instantiate a CodeMemberField //object for each constant value. Assign a sequential number as a value, //and indicate that it is a public constant that we desire foreach (string szConstant in oConstant) {

CodeMemberField oCodeMemberField =

new CodeMemberField(typeof(int), szConstant); oCodeMemberField.InitExpression =

new CodePrimitiveExpression(iCnt++); oCodeMemberField.Attributes =

MemberAttributes.Public | MemberAttributes.Const; oCodeTypeDeclaration.Members.Add(oCodeMemberField);

This outputs the following code: public const int Car = 0;

public const int Bus = 1; public const int Limo = 2; public const int Tank = 3;

0 0

Post a comment