I recently got into bother because of my rather lax use of variable names in some example code. As someone who has the job of writing code samples that programmers like you are going to read when you glimpse at the C# documentation, it’s important that I at least set a good example. So I read up on the
Will your choice of naming convention stop your code from compiling? No. Will your choice of names make your code run faster? No.
What a consistent naming convention will do is make it easier for you when to go back to look at your code, trying to work out what is going on. And if everyone sticks to the same naming style, it will make it easier when you look at someone else’s code, and easier when they read yours.
If you came to C# from C++, you might be used to “Hungarian” naming convention. This convention included a little bit of the variable type in the variable name itself, as a clue. So a string variable might be called “strMyName” for example. Now, as C# is a strongly typed language, this isn’t really necessary – if Intellisense doesn’t spot it, the compiler sure as heck will.
All this information comes from a section in the MSDN docs called Naming Guidelines, and here are the highlights. Firstly, don’t use underscores. And then follow these specific examples:
[Edit: Using underscores is actually acceptable, except in classes and interfaces. At least, underscores aren’t specifically banned elsewhere.]
The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design: e.g. Microsoft.Media.Design.
Use a noun or noun phrase, and Pascal case. Don’t use special letters (F or C) to precede the name (this isn’t MFC ;-). Examples: Button, FileStream.
Use a noun or noun phrase, and Pascal case. Start the name with a capital I. For example, IServiceProvider, IFormatable.
Use descriptive names, and Camel casing. For example, typeName, personName, personAge.
Use verbs or verb phrases, and Pascal case. For example, RemoveAll(), GetFileData().
Use a noun or noun phrase and Pascal case. For example, BackColor.
If a name is in Pascal case, it starts with a capital letter, and so do any other words that make up the name. For example, BackColor.
If a name is in Camel case, then it starts with a lower case letter, and the first letter of every subsequent word is in upper case. For example, trouserPress.