In C #, how do you do the same thing as #define

Based on background C, I use to determine the size of the buffer as follows:

#define BUFFER_SIZE 1024

uint8_t buffer[BUFFER_SIZE];

How would you do the same in C #?

Is K & R's all-caps style also suitable with the usual C # Pascal / Camel case?

+3
source share
5 answers
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.

+5
source

Personally, I prefer constants:

private const int BUFFER_SIZE = 1024;

Although, if it is publicly available, and you are a framework, you might want it to be readonly to avoid recompiling the client .

+5
source
public static readonly int BUFFER_SIZE = 1024;

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

+3
source

Do not use #define.

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

+1
source

In C #, I decided to do it like this:

//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];
0
source

Source: https://habr.com/ru/post/1702394/


All Articles