> One solution is to create a class with all static const variables (it
that
> even allowed?).

This is pretty much exactly what const fields are for. E.g.

class Foo
{
   public const int THIS_VAL = 10;
   public const int MAX_THAT = 255;

   static void Main()
   {
     Console.WriteLine(MAX_THAT - THIS_VAL);
   }
}

> 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 "assignment" is done at compile time. I quote because there's never
really any IL emitted to set some piece of memory equal to 10 or to 255.
Rather, there's some metadata that says, "The symbol THIS_VAL is
equivalent to 10." In fact, it's illegal to assign a const field to a
value that *can't* be known at compile time. So

public const int THIS_VAL = 3 * 5;

is okay, but

public const int THIS_VAL = RandomGenerator.Next();

is not. Note that the readonly keyword gives you the latter. See the
docs for more detail.

> The second is that this class takes up memory.

const fields are static, and therefore take up only 4 bytes per
AppDomain (assuming int), not 4 bytes per Foo instance. Which is pretty
acceptable given the fact that you've already agreed to load the CLR.


> -----Original Message-----
> From: Moderated discussion of advanced .NET topics. [mailto:ADVANCED-
> [EMAIL PROTECTED]] On Behalf Of Noam Arbel
> Sent: Wednesday, July 03, 2002 7:42 PM
> To: [EMAIL PROTECTED]
> Subject: [ADVANCED-DOTNET] Defining fixed variables
>
> Hello,
>
> I have a conceptual question:
>
> In C++ we used to do
>
> #define THIS_VAL 10
> #define MAX_THAT 255
>
> and so on. Those where substituted by the compiler with no runtime
cost.
>
> Is the an equivalent in C#?
>
>
> Any better ideas?
>
>
> thanks,
>
> Noam
>
> You can read messages from the Advanced DOTNET archive, unsubscribe
from
> Advanced DOTNET, or
> subscribe to other DevelopMentor lists at http://discuss.develop.com.

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