Justin Tanner
Justin Tanner

Reputation: 14352

In C# how do you accomplish the same thing as a #define

Coming from a C background I'm used to defining the size of the buffer in the following way:

#define BUFFER_SIZE 1024

uint8_t buffer[BUFFER_SIZE];

How would you do the accomplish the same thing in C#?

Also does the all-caps K&R style fit in with normal C# Pascal/Camel case?

Upvotes: 3

Views: 1194

Answers (5)

MrHIDEn
MrHIDEn

Reputation: 1879

In C#, I decided to do that this way:

//C# replace C++ #define
struct define
{
    public const int BUFFER_SIZE = 1024;
    //public const int STAN_LIMIT = 6;
    //public const String SIEMENS_FDATE = "1990-01-01";
}

//some code
byte[] buffer = new byte[define.BUFFER_SIZE];

Upvotes: 0

ctacke
ctacke

Reputation: 67178

public static readonly int BUFFER_SIZE = 1024;

I prefer this over a const due to the compiler shenanigans that can happen with a const value (const is just used for replacement, so changing the value will not change it in any assembly compiled against the original).

Upvotes: 3

Mark Brackett
Mark Brackett

Reputation: 85645

Personally, I prefer constants:

private const int BUFFER_SIZE = 1024;

Though, if it's public and you're a framework, you may want it to be a readonly to avoid client recompiles.

Upvotes: 5

Jader Dias
Jader Dias

Reputation: 90465

const int BUFFER_SIZE = 1024;

Do not use "static readonly" because it creates a variable. "const" are replaced at build time and do not create variables.

Upvotes: 5

Megacan
Megacan

Reputation: 2518

Don't use #define.

Define a constante: private const int BUFFER_SIZE or readonly variable: private readonly int BUFFER_SIZE

Upvotes: 1

Related Questions