tags:

views:

374

answers:

4

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?

+3  A: 
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).

ctacke
I agree. I learned this from Effective C# : Item 2 - Prefer readonly to const.
Bobby Cannon
+1  A: 

Don't use #define.

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

Megacan
+5  A: 
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.

Jader Dias
I consider this poor form. If I have this is assembly A, and assembly B references it it can leads to unexpected behavior. Change the value in assembly A and recompile and the old value will continue to be used in assembly B unless it is recompiled.
ctacke
@ctacke This is exactly analogous to a #define in a C header file - every module that used it would need to be recompiled if its value changed. I agree with Vernicht +1
Stu Mackellar
@ctacke: thats why I use constants with the PRIVATE modifier
Jader Dias
@Stu Mackellar, Vernicht: I agree with ctacke. Using const is ok but you must ensure that you are not sharing across assemblies. If you go public make sure you are using readonly! Reference: Effective C# : Item 2 - Prefer readonly to const
Bobby Cannon
+5  A: 

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.

Mark Brackett
Interesting - you prefer the const, even knowing the inherent danger?
ctacke
If it is private to the assembly, there's no benefit for using the readonly variable over the constant. There's only a danger if the constant is exposed to other assemblies.
Steve Mitcham
Also: it's hard to imagine a case where you're distributing a framework and users of your framework wouldn't need to recompile for the new version anyway.
Joel Coehoorn
@ctacke - making the const private or internal solves that problem...very rarely would I ever expose a const as public. Besides that, I don't tend to make frameworks - so I expect dependent assemblies to recompile anyway.
Mark Brackett
Lots of "hard to imagine" and "rarely" items here. If experience has taught me nothing in software development, it's always the rare bugs that bite me in the ass. Getting in the habit of using a static read-only means I never have to think about "what if" or someone else changing the scope.
ctacke