538
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?

dove
  • 20,469
  • 14
  • 82
  • 108
mmiika
  • 9,970
  • 5
  • 28
  • 34
  • 4
    @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.) – Peter Mortensen Feb 03 '10 at 11:26
  • 11
    @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](http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29). – Albireo May 19 '11 at 10:02
  • @PeterMortensen That's creative! But names like itsEmployee and itsCostumer sound like they could be misleading. – Camilo Martin Mar 29 '12 at 00:37
  • 5
    MSDN: Capitalization Conventions http://msdn.microsoft.com/en-us/library/vstudio/ms229043(v=vs.90).aspx – Captain Sensible Mar 25 '13 at 09:15
  • 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 :( – nawfal Oct 22 '13 at 07:27
  • **Related:** [Naming local constants: UpperCamelCase or lowerCamelCase?](http://stackoverflow.com/q/3157431/1497596) – DavidRR Sep 13 '14 at 17:21
  • 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). – BrainSlugs83 Feb 29 '16 at 21:55
  • Why is `Math.PI` in upper case? – mr5 Jun 27 '18 at 05:54
  • 1
    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. – Léon Pelletier Aug 28 '18 at 17:41

9 Answers9

639

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.

Morse
  • 8,258
  • 7
  • 39
  • 64
Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • 62
    Actually, StyleCop is "not a Microsoft product," but "a tool developed by a very passionate developer at Microsoft (on evenings and weekends)." (See http://blogs.msdn.com/sourceanalysis/archive/2008/07/20/clearing-up-confusion.aspx and http://blogs.msdn.com/bharry/archive/2008/07/19/clearing-up-confusion.aspx) 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. – bdukes Nov 23 '09 at 21:36
  • 17
    @bdukes - 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). – Greg Beech Nov 23 '09 at 23:36
  • 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 (-: – Murph Feb 03 '10 at 11:24
  • 10
    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. – Efrain May 11 '11 at 09:06
  • 68
    I'd go with TheAnswer notation except when the value is 42, in which case I'd definately stick with the ALL_CAPS approach. – Benoittr Jun 02 '11 at 21:29
  • 1
    Pascal is better because it doesn't require the _, which takes far to much hand effort to type constantly. – Rob Oct 13 '12 at 02:31
  • 6
    Shouldn't a private field be camel cased, event if it's const? – Markus Meyer Jan 27 '13 at 15:15
  • @MarkusMeyer No, just like method names and properties, it should be "TitleCase", regardless of visibility. – BrainSlugs83 Feb 29 '16 at 21:58
  • 1
    Microsoft guidelines say "Do not use uppercase letters for field names": https://msdn.microsoft.com/en-us/library/ta31s3bc.aspx – Markus Meyer Mar 02 '16 at 20:59
  • 3
    That's true for instance fields. Constants are considered static for the purposes of naming. https://msdn.microsoft.com/en-us/library/x2dbyw72.aspx – Greg Beech Mar 03 '16 at 06:17
110

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;
 }
JohnB
  • 18,046
  • 16
  • 98
  • 110
usefulBee
  • 9,250
  • 10
  • 51
  • 89
  • 10
    I, too, prefer this as Pascal casing can easily be confused with a property reference. – bc3tech Apr 10 '15 at 17:04
  • 9
    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. – dub stylee Nov 23 '15 at 23:59
  • 34
    @usefulBee "SNAKE_CASE" is strongly discouraged in C#; This answer is wrong. The correct case for consts in C# is "TitleCase". – BrainSlugs83 Feb 29 '16 at 22:01
  • 5
    @usefulBee 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. – Per Lundberg Feb 24 '17 at 22:10
80

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.

bh213
  • 6,343
  • 9
  • 43
  • 52
27

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.

Treb
  • 19,903
  • 7
  • 54
  • 87
  • 41
    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. – Greg Hewgill Oct 28 '08 at 08:26
  • 3
    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? – mmiika Oct 28 '08 at 08:34
  • 5
    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. – Tim Long May 09 '09 at 05:38
  • 7
    @Tim: I agree, in the end preprocessor macros brought more harm than good. My most favourite PP macro: "#DEFINE Private Public" ;-) – Treb May 09 '09 at 11:44
  • 1
    @Tim: the C++ Standard Tempate Library has adopted lower case for constants e.g. std::string::npos (http://www.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#. – Richard Dingwall Nov 03 '10 at 13:08
  • 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. – Ishikawa Jun 13 '23 at 11:20
19

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.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
  • 1
    The developer who wrote that article was clearly not following the Microsoft recommended styling conventions for C#. – BrainSlugs83 Feb 29 '16 at 22:37
  • 4
    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. – Metalogic Dec 03 '19 at 19:07
  • Dude, in Calendar3, your examples are not public constants, they are private by default. Thus, camelCase is the right way to go. – Paul-Sebastian Manole Apr 20 '22 at 18:44
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.

user31939
  • 263
  • 1
  • 3
16

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dove
  • 20,469
  • 14
  • 82
  • 108
  • 3
    In this specific case it is *the* answer. But only because I love to read D.Adams so much. – Treb Oct 28 '08 at 08:22
  • yes, but what's the question? and don't feed me that sorry for the inconvenience line ;) – dove Oct 28 '08 at 08:26
  • 3
    Ah, but since you already know the answer, you cannot know the question. They are mutually exclusive. (Bet you already knew that ;-) – Treb Oct 28 '08 at 08:28
  • This is the correct answer to the OP's question. -- I'd upvote you twice for removing the `The` if I could. :-) – BrainSlugs83 Feb 29 '16 at 22:35
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John
  • 29,788
  • 18
  • 89
  • 130
10

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900