Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming Windows API constants in C#

The naming convention for constants in C# is Pascal casing:

private const int TheAnswer = 42;

But sometimes we need to represent already-existing constants from the Windows API.

For example, I don't know how to name this:

/// <summary>
/// With this style turned on for your form, 
/// Windows double-buffers the form and all its child controls.
/// </summary>
public const int WS_EX_COMPOSITED = 0x02000000;

What should I name it?

Keeping it as WS_EX_COMPOSITED allows me to quickly associate it with the WinAPI, but it's wrong.

Some options:

  • WsExComposited -- Too hungarian
  • Composited -- Too short
  • WsEx enum with Composited in it -- Still hungarian
  • ExtendedWindowsStyles.Composited -- Constant in a class? Enum?

It should be noted that the objectives for a good naming are:

  • It must be readable.
  • It must not trigger FxCop and StyleCop, even if that means hiding it from them.
like image 506
Camilo Martin Avatar asked Mar 29 '12 01:03

Camilo Martin


People also ask

How do you name a constant?

Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.

How do you declare a constant in C sharp?

Constants are declared with the const modifier. Only the C# built-in types (excluding System. Object) may be declared as const . User-defined types, including classes, structs, and arrays, cannot be const .

How do you keep a constant in C#?

Syntax of Constant in C# We have to use "const" keyword to declare constant variable. Constants are effectively static because the value of the constant is the same in all instances of the class but you can declare constants without a static keyword an example is shown below. Display Output : PI Value is : 3.14.

Should constants be capitalized C#?

C# convention is not to use uppercase for constants.


1 Answers

WS_EX_COMPOSITED is perfectly fine for part that directly interfaces with Win API (or any other documented API for that matter). The portion that you want to expose should follow standard conventions - have separate public facade to call native functions with good method names (you'll eventually forget what you've researched about particular combinations of flags, but good wrapper method name will at least let you use it).

The side benefit of keeping the name as close as possible to native API is that you can search for constant directly in the MSDN/other documentation and find answer immediately. It will be much harder if you rename it.

like image 115
Alexei Levenkov Avatar answered Oct 16 '22 11:10

Alexei Levenkov