Sponsored Ad

Thursday, December 24, 2009

Create an constant array in c#

Strictly speaking you can not, since the constellation can only be applied to a field or local whose value is known at compile time.

In both the lines below, the right-hand is not a constant expression (not in C#).

  1. const int [] constIntArray = newint [] {2, 3, 4};
  2. // error CS0133: The expression being assigned to 'constIntArray' must be constant
  3. const int [] constIntArrayAnother = {2, 3, 4};
  4. // error CS0623: Array initializers can only be used in a variable or field
  5. //               initializer. Try using a new expression instead.

However, there are some workarounds, depending on what it is you want to achieve.

If want a proper .NET array (System.Array) that cannot be reassigned, then static readonly will do for you.

static readonly int [ ] constIntArray = new int[] {1, 2, 3};

The constIntArray field will be initialized before it its first use.

If, however, requires a constant set of values (such as an argument to an attribute constructor), then - if you may be limited to integral types - an enum would serve well.

For example:

  1. [Flags]
  2. public enum Role
  3. {
  4.     Administrator = 1,
  5.     BackupOperator = 2,
  6.     // etc.
  7. }
  8.  
  9. public class RoleAttribute : Attribute
  10. {
  11.     public RoleAttribute()
  12.     {
  13.         CreateRole = DefaultRole;
  14.     }
  15.  
  16.     public RoleAttribute(Role role)
  17.     {
  18.         CreateRole = role;
  19.     }
  20.  
  21.     public Role CreateRole
  22.     {
  23.         get { return this.createRole; }
  24.         set { this.createRole = value; }
  25.     }
  26.  
  27.     private Role createRole = 0;
  28.     public const Role DefaultRole = Role.Administrator
  29.      | Role.BackupOperator;
  30. }
  31.  
  32. [RoleAttribute(RoleAttribute.DefaultRole)]
  33. public class DatabaseAccount
  34. {
  35.     //..............
  36. }

RoleAttribute, instead of taking a series, only have a single argument of the flags (appropriately or-ed). If the underlying type of the list is long or ulong paper, which offers 64 different functions.

1 comments:

Sponsored Ad

More Related Articles

Website Update

Followers