Some time ago, Noam Arbel wrote...

>#define THIS_VAL 10
>#define MAX_THAT 255
>
>One solution is to create a class with all static const variables (it that
>even allowed?). But there are 2 issues with that; one is that the
>assignment is done at runtime (or is the compiler smart enough to assign
>at compile time). The second is that this class takes up memory.

This solution is correct.  First of all, csc is smart enough to optimize
the assignment, even in the debug build.  Second, this class does not
occupy memory since const fields are stored in metadata and not constructed
in the class static constructor (generated by the compiler).

Being picky, the class will get a constructor delegating to the System::
Object constructor, and thus eating up 3 or 4 IL bytes, JIT compiler
resources and about 20 bytes of code space :)  You can easily avoid
this by declaring a struct instead of a class.

So, the final code is:

public struct MyConst
{
   public const int THIS_VAL = 10;
}

public class Test
{
   public int ThisVal
   {
     get { return MyConst.THIS_VAL; }
   }
}

As ildasm shows, there is no code or data associated with struct MyConst,
only a metadeclaration

.field public static literal int32 THIS_VAL = int32(0x0000000A)

and the getter for ThisVal looks like this:

.method public hidebysig specialname instance int32
         get_ThisVal() cil managed
{
   // Code size       3 (0x3)
   .maxstack  8
   IL_0000:  ldc.i4.s   10   /* Load the constant 10 - compiler resolves it! */
   IL_0002:  ret
} // end of method Test::get_ThisVal

  -kkm

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to