C# naming convention for constants?
Asked Answered
P

9

552
private const int THE_ANSWER = 42;

or

private const int theAnswer = 42;

Personally I think with modern IDEs we should go with camelCase as ALL_CAPS looks strange. What do you think?

Pilaf answered 28/10, 2008 at 8:16 Comment(9)
@mmiika: what is the meaning "the" in this example? Is it as in "The Hitchhiker's Guide to the Galaxy" or is it carry over from some C++ coding standard? (E.g. an old C++ framework for Macintosh, THINK C [and later, Symantec C++], used prefix "its" for pointer/reference members and "the" for scalar members.)Skerry
@Peter, since the value of the constant is 42, I strongly belive it's a reference to the The Hitchhiker's Guide to the Galaxy.Christi
@PeterMortensen That's creative! But names like itsEmployee and itsCostumer sound like they could be misleading.Porphyritic
MSDN: Capitalization Conventions msdn.microsoft.com/en-us/library/vstudio/ms229043(v=vs.90).aspxAzaleeazan
I prefer theAnswer. Previously been a Hungarian notation fan, but ever since I learned to not use it, I love to strictly avoid any meta indication in naming. Same goes for interfaces like IInterface. I prefer Interfacable. But when working in a team, I got to comply with rules :(Armidaarmiger
Related: Naming local constants: UpperCamelCase or lowerCamelCase?Billman
MSDN recommends using "TitleCase" for constants, so it would be "TheAnswer" (though, as others have commented you generally shouldn't prefix your variable names with "The", as it does not add any value).Plumbism
Why is Math.PI in upper case?Newfeld
The problem with the answers here is that the examples are one/two-words variables. But when you come accross a very specific definition for a value that is used application-wide, like Temporary_Employee_Subscription_January_Grace_Period, or anything that points to a very specific property of a category in a particular business logic case, then the readability of the definition is affected when removing underscores: TemporaryEmployeeSubscriptionJanuaryGracePeriod. For me, this is a distinct type of constants that is not like your common "Enum"-type of constants.Inhospitable
M
656

The recommended naming and capitalization convention is to use PascalCasing for constants (Microsoft has a tool named StyleCop that documents all the preferred conventions and can check your source for compliance - though it is a little bit too anally retentive for many people's tastes). e.g.

private const int TheAnswer = 42;

The Pascal capitalization convention is also documented in Microsoft's Framework Design Guidelines.

Maeda answered 28/10, 2008 at 8:25 Comment(11)
Actually, StyleCop is "not a Microsoft product," but "a tool developed by a very passionate developer at Microsoft (on evenings and weekends)." (See blogs.msdn.com/sourceanalysis/archive/2008/07/20/… and blogs.msdn.com/bharry/archive/2008/07/19/…) for details.) That being said, the Microsoft's framework naming conventions use Pascal casing for constants, so the tool is just enforcing the standard that Microsoft does publish and endorse.Lyrebird
@Lyrebird - I didn't say it was a Microsoft product, however it does have quite a lot of usage and support throughout the organisation (as a former employee, I was using it years before anybody outside Microsoft got their hands on it, so I'm well aware of its heritage).Maeda
Worth noting that you can easily switch StyleCop rules off and do so in a way thats flexible across files, projects and solutions. In theory you can add your own rules too. In theory (-:Highflier
I don't like this, because the first letter is typically used to indicate whether a variable is externally visible or not. In the code, TheAnswer looks like a public property, not a private const to me. I would actually prefer to go with a prefix like constTheAnswer and ConstTheAnswer.Grattan
I'd go with TheAnswer notation except when the value is 42, in which case I'd definately stick with the ALL_CAPS approach.Gynandry
Pascal is better because it doesn't require the _, which takes far to much hand effort to type constantly.Earwitness
Shouldn't a private field be camel cased, event if it's const?Coulee
@MarkusMeyer No, just like method names and properties, it should be "TitleCase", regardless of visibility.Plumbism
Microsoft guidelines say "Do not use uppercase letters for field names": msdn.microsoft.com/en-us/library/ta31s3bc.aspxCoulee
That's true for instance fields. Constants are considered static for the purposes of naming. msdn.microsoft.com/en-us/library/x2dbyw72.aspxMaeda
Where in the linked design guidelines is there any mention of private constants?Appoint
O
114

Visually, Upper Case is the way to go. It is so recognizable that way. For the sake of uniqueness and leaving no chance for guessing, I vote for UPPER_CASE!

const int THE_ANSWER = 42;

Note: The Upper Case will be useful when constants are to be used within the same file at the top of the page and for intellisense purposes; however, if they were to be moved to an independent class, using Upper Case would not make much difference, as an example:

public static class Constant
{
    public static readonly int Cons1 = 1;
    public static readonly int coNs2 = 2;
    public static readonly int cOns3 = 3;
    public static readonly int CONS4 = 4;
}

// Call constants from anywhere
// Since the class has a unique and recognizable name, Upper Case might lose its charm
private void DoSomething(){
var getCons1 = Constant.Cons1;
var getCons2 = Constant.coNs2;
var getCons3 = Constant.cOns3;
var getCons4 = Constant.CONS4;
 }
Osric answered 21/5, 2014 at 15:34 Comment(4)
I, too, prefer this as Pascal casing can easily be confused with a property reference.Uhland
Regardless of the recommendations above, I prefer the UPPER_CASE for constants as well, as it makes them much easier to identify compared to any of the other cases.Danu
@Osric "SNAKE_CASE" is strongly discouraged in C#; This answer is wrong. The correct case for consts in C# is "TitleCase".Plumbism
@Osric Agree. But it's still good to mark what is the consensus way of writing it though. I have been doing loads of Ruby code lately, and I think the SCREAMING_SNAKE_CASE makes sense: it's very obvious that it's something special, and you don't even need to hover/Go To Definition to find out what it's about. You know it immediately.Croon
M
83

Actually, it is

private const int TheAnswer = 42;

At least if you look at the .NET library, which IMO is the best way to decide naming conventions - so your code doesn't look out of place.

Mamiemamma answered 28/10, 2008 at 8:23 Comment(0)
F
26

I still go with the uppercase for const values, but this is more out of habit than for any particular reason.

Of course it makes it easy to see immediately that something is a const. The question to me is: Do we really need this information? Does it help us in any way to avoid errors? If I assign a value to the const, the compiler will tell me I did something dumb.

My conclusion: Go with the camel casing. Maybe I will change my style too ;-)

Edit:

That something smells hungarian is not really a valid argument, IMO. The question should always be: Does it help, or does it hurt?

There are cases when hungarian helps. Not that many nowadays, but they still exist.

Farmhouse answered 28/10, 2008 at 8:21 Comment(6)
Code is read much more often than it is written. Sure, when you're writing the code the compiler will prevent you from assigning to a constant. But what about the guy who has to maintain your code two years from now? It's sure nice to be able to recognise a constant immediately.Loxodromic
The IDEs of today catch a lot of problems before compilation. I don't think recognizing constant by name is important, otherwise shouldn't you add some special name for readonly variables as well?Pilaf
If you think about it, the uppercase habbit probably came from preprocessor macros rather than constants (I've never used block caps for true constants). In that context, it makes sense to distinguish the macros from the actual code because a macro may well actually be an expression and not a constant value, its expansion may cause side effects and so on. So you need to know when you're using a macro and when you're using a const. I'm personally glad to see the back of preprocessor macros, they had a lot of potential to make code hard to read.Doodlebug
@Tim: I agree, in the end preprocessor macros brought more harm than good. My most favourite PP macro: "#DEFINE Private Public" ;-)Farmhouse
@Tim: the C++ Standard Tempate Library has adopted lower case for constants e.g. std::string::npos (cplusplus.com/reference/string/string/npos). So ALL_CAPS is only for macros and preprocessor directives- which makes it look even more stupider in C#.Fitzhugh
In my opinion the uppercase is still because it improves readability and coding. For instance, consider the case when you need to refer a constant but you don't know its complete name : you will start typing the words you know and the intellisense will show. If you had declared your const in camelCase, you will have to hover every result to figure out if it's your const, whereas you'd spot it immediately if it was writter in upper case.Unlovely
B
21

In its article Constants (C# Programming Guide), Microsoft gives the following example:

class Calendar3
{
    const int months = 12;
    const int weeks = 52;
    const int days = 365;

    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}

So, for constants, it appears that Microsoft is recommending the use of camelCasing. But note that these constants are defined locally.

Arguably, the naming of externally-visible constants is of greater interest. In practice, Microsoft documents its public constants in the .NET class library as fields. Here are some examples:

The first two are examples of PascalCasing. The third appears to follow Microsoft's Capitalization Conventions for a two-letter acronym (although pi is not an acryonym). And the fourth one seems to suggest that the rule for a two-letter acryonym extends to a single letter acronym or identifier such as E (which represents the mathematical constant e).

Furthermore, in its Capitalization Conventions document, Microsoft very directly states that field identifiers should be named via PascalCasing and gives the following examples for MessageQueue.InfiniteTimeout and UInt32.Min:

public class MessageQueue
{
    public static readonly TimeSpan InfiniteTimeout;
}

public struct UInt32
{
    public const Min = 0;
}

Conclusion: Use PascalCasing for public constants (which are documented as const or static readonly fields).

Finally, as far as I know, Microsoft does not advocate specific naming or capitalization conventions for private identifiers as shown in the examples presented in the question.

Billman answered 2/1, 2014 at 19:42 Comment(3)
The developer who wrote that article was clearly not following the Microsoft recommended styling conventions for C#.Plumbism
The article pointed to by this answer has changed. The consts are now public and have been PascalCased. Given both those changes, this does not help answer whether private constants should be PascalCased or camelCased.Cantor
Dude, in Calendar3, your examples are not public constants, they are private by default. Thus, camelCase is the right way to go.Prognostication
J
19

First, Hungarian Notation is the practice of using a prefix to display a parameter's data type or intended use. Microsoft's naming conventions for says no to Hungarian Notation http://en.wikipedia.org/wiki/Hungarian_notation http://msdn.microsoft.com/en-us/library/ms229045.aspx

Using UPPERCASE is not encouraged as stated here: Pascal Case is the acceptable convention and SCREAMING CAPS. http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming

Microsoft also states here that UPPERCASE can be used if it is done to match the the existed scheme. http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx

This pretty much sums it up.

Jolinejoliotcurie answered 28/10, 2008 at 10:37 Comment(1)
Yes, Hungarian notation is not all caps.Theft
S
15

Leave Hungarian to the Hungarians.

In the example I'd even leave out the definitive article and just go with

private const int Answer = 42;

Is that answer or is that the answer?

*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to life, the universe and everything.

Seaborg answered 28/10, 2008 at 8:19 Comment(4)
In this specific case it is the answer. But only because I love to read D.Adams so much.Farmhouse
yes, but what's the question? and don't feed me that sorry for the inconvenience line ;)Seaborg
Ah, but since you already know the answer, you cannot know the question. They are mutually exclusive. (Bet you already knew that ;-)Farmhouse
This is the correct answer to the OP's question. -- I'd upvote you twice for removing the The if I could. :-)Plumbism
C
10

The ALL_CAPS is taken from the C and C++ way of working I believe. This article here explains how the style differences came about.

In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary.

The FxCop and Microsoft StyleCop software will help give you guidelines and check your code so everyone works the same way.

Corymb answered 28/10, 2008 at 8:21 Comment(0)
I
10

I actually tend to prefer PascalCase here - but out of habit, I'm guilty of UPPER_CASE...

Ingravescent answered 28/10, 2008 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.