Paul Michaels
Paul Michaels

Reputation: 16695

#Define Compiler Directive in C#

In C, I could declare a compiler directive as follows:

#define MY_NUMBER 10

However, in C#, I only appear to be able to do this:

#define MY_NUMBER

Which is obviously useless in this case.

Is this correct, or am I doing something wrong? If not, can anyone suggest a way of doing this, either at namespace or solution level? I thought of maybe creating a static class, but that seems to be overkill for one value.

Upvotes: 7

Views: 5572

Answers (6)

TheCodeArtist
TheCodeArtist

Reputation: 22487

Use public const


AFAIK,

C# does not use pre-processor defines to perform replacement in code, so you have to use a constant.

This should do the trick:

public const int MY_NUMBER = 10;

Upvotes: 1

Arto Viitanen
Arto Viitanen

Reputation: 188

You might also like to check enums, like

enum Numbers
{
    Nothing = 0,
    Dads = 5,
    My = 10,
    LittleJims = 25
}

So, instead of C's MY_NUMBER, you have Numbers.My.

Upvotes: 1

josef.axa
josef.axa

Reputation: 1173

A lot of the other answers suggest using a public const field. Note however that a public const will be compiled into assemblies referencing it, forcing you to recompile not only the assembly it is defined in but also every assembly referencing it if you ever change the value of the const.

If you are not certain the value will never have to change, a public static readonly field is a better alternative.

Upvotes: 5

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59923

Yes, it is correct.

Here's a quote from the MSDN documentation:

The pre-processing directives provide the ability to conditionally skip sections of source files, to report error and warning conditions, and to delineate distinct regions of source code. The term "pre-processing directives" is used only for consistency with the C and C++ programming languages. In C#, there is no separate pre-processing step; pre-processing directives are processed as part of the lexical analysis phase.

So you can't really define compiler constants, like in C and C++.

Related resources:

Upvotes: 6

Thomas
Thomas

Reputation: 8003

You can define a const or a static readonly, and if you want it conditionally you can wrap it in an #if directive

#if DEBUG
private const int MY_NUMBER = 10;
#else
private const int MY_NUMBER = 20;
#endif

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

Yes, you're correct. const and readonly are really your only options.

Upvotes: 3

Related Questions