ChatGPT解决这个技术问题 Extra ChatGPT

C# naming convention for constants?

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?

@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, since the value of the constant is 42, I strongly belive it's a reference to the The Hitchhiker's Guide to the Galaxy.
@PeterMortensen That's creative! But names like itsEmployee and itsCostumer sound like they could be misleading.
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.

M
Morse

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.


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.
@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).
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.
I'd go with TheAnswer notation except when the value is 42, in which case I'd definately stick with the ALL_CAPS approach.
Shouldn't a private field be camel cased, event if it's const?
J
JohnB

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;
 }

I, too, prefer this as Pascal casing can easily be confused with a property reference.
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.
@usefulBee "SNAKE_CASE" is strongly discouraged in C#; This answer is wrong. The correct case for consts in C# is "TitleCase".
@BrainSlugs83, I don't think there is right or wrong here; it comes down to preference and what makes the code clearer.
@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.
b
bh213

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.


T
Treb

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.


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.
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?
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: I agree, in the end preprocessor macros brought more harm than good. My most favourite PP macro: "#DEFINE Private Public" ;-)
@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#.
u
user31939

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.


Yes, Hungarian notation is not all caps.
D
DavidRR

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:

Int32.MaxValue

String.Empty (actually, static readonly)

Math.PI

Math.E

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.


The developer who wrote that article was clearly not following the Microsoft recommended styling conventions for C#.
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.
Dude, in Calendar3, your examples are not public constants, they are private by default. Thus, camelCase is the right way to go.
P
Peter Mortensen

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.


In this specific case it is the answer. But only because I love to read D.Adams so much.
yes, but what's the question? and don't feed me that sorry for the inconvenience line ;)
Ah, but since you already know the answer, you cannot know the question. They are mutually exclusive. (Bet you already knew that ;-)
This is the correct answer to the OP's question. -- I'd upvote you twice for removing the The if I could. :-)
P
Peter Mortensen

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.


M
Marc Gravell

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