|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
Introduction
When I was looking for a standard convention for generics, I came across a 50-page manual for coding standards for C#. I am sure that, apart from the author, there are few who actually go through and read all of them. So, I thought of coming up with this article. I have tried to comprehend the essential facts which we developers sometimes neglect in C#. I will also discuss some common pitfalls.
Small, Sweet and Simple.
That's how I describe it. I hope you enjoy reading.
Why Coding Standards
Simple: maintainability. If, 6 months down the line, your customer isn't too happy with the product and wants an enhancement in the application you have created, you should be able to do it without introducing new bugs. There are a lot of other good reasons, but this is the one which concerns us more than anything else.
Not following any standard is like going with a temporary solution (which might lead to a permanent problem) and, as you will see, it takes less effort to keep in mind a few simple measures than to do haphazard coding.
All you have to do is study good standards once and keep them in the back of your head. Trust me; it's worth it.
Contents
1. Naming - What is meant by meaningful names 2. Casing - When to use PascalCase and when camelCase 4. Generics - Proper usage 5. Delegates - Proper usage 6. Miscellaneous - Some short tidbits 7. Common Pitfalls - Mistakes we should watch out for 8. References - Where to get more information
Naming
"The beginning of wisdom is to call things by their right names" - Chinese Proverb
"Meaningful" is the keyword in naming. By meaningful names, I mean concise names that accurately describe the variable, method or object. Let's see how this would be in C#:
Namespaces - Names should be meaningful and complete. Indicate your company or name, product and then your utility. Do not abbreviate.
namespace CompanyName.ProductName.Utility
namespace CN.PROD.UTIL
Classes - Class names should always be a noun and, again, should be meaningful. Avoid verbs
class Image
{
...
}
class Filters
{
...
}
class Act
{
...
}
class Enhance
{
...
}
Methods - Always use a verb-noun pair, unless the method operates on its containing class, in which case, use just a verb.
public void InitializePath();
public void GetPath();
public void ShowChanges();
public void System.Windows.Forms.Form.Show();
public void Path();
public void Changes();
Methods with return values - The name should reflect the return value.
public int GetImageWidth(Bitmap image);
public int GetDimensions(Bitmap image);
Variables - Do not abbreviate variable names. Variable names should again be descriptive and meaningful.
int customerCount = 0;
int index = 0;
string temp = "";
int cc = 0;
int i = 0;
string t = "";
Private member variables - Prefix class member variables with m_.
public class Image
{
private int m_initialWidth;
private string m_filename;
...
}
Interfaces - Prefix all interface names with I. Use a name that reflects an interface's capabilities, either a general noun or an "-able".
interface IClock
{
DateTime Time { get; set; }
...
}
interface IAlarmClock : IClock
{
void Ring();
DateTime AlarmTime { get; set; }
...
}
interface IDisposable
{
void Dispose();
}
interface IEnumerable
{
IEnumerator GetEnumerator();
}
Custom attributes - Suffix all attribute class names with Attribute. The C# compiler recognizes this and allows you to omit it when using it.
public class IsTestedAttribute : Attribute
{
public override string ToString()
{
return "Is Tested";
}
}
[IsTested]
public void Ring();
Custom exceptions - Suffix all custom exception names with Exception.
public class UserNotExistentException :
System.ApplicationException
{
...
}
Delegates - Suffix all event handlers with Handler; suffix everything else with Delegate.
public delegate void ImageChangedHandler();
public delegate string StringMethodDelegate();
Casing
C# standards dictate that you use a certain pattern of Pascal Casing (first word capitalized) and Camel Casing (all but first word capitalized).
Pascal Casing - use PascalCasing for classes, types, methods and constants.
public class ImageClass
{
const int MaxImageWidth = 100;
public void ResizeImage();
}
enum Days
{
Sunday,
Monday,
Tuesday,
...
}
Camel Casing - use camelCasing for local variables and method arguments.
int ResizeImage(int imageCount)
{
for(int index = 0; index < imageCount; index++)
{
...
}
}
Generics
Generics, introduced in .NET 2.0, are classes that work uniformly on values of different types.
Use capital letters for types; don't use "Type" as a suffix.
public class Stack ‹T›
public class Stack ‹t›
public class Stack ‹Type›
Delegates
Use delegate inference instead of explicit delegate instantiation.
public delegate void ImageChangedDelegate();
public void ChangeImage()
{
...
}
ImageChangedDelegate imageChanged = ChangeImage;
ImageChangedDelegate imageChanged =
new ImageChangedDelegate(ChangeImage);
Use empty parenthesis on anonymous methods without parameters.
public delegate void ImageChangeDelegate();
ImageChangedDelegate imageChanged = delegate()
{
...
}
Miscellaneous
- Avoid putting
using statements inside a namespace
- Check spelling in comments
- Always start left curly brace { on a new line
- Group framework namespaces together; add custom and thirdparty namespaces below
- Use strict indentation (3 or 4 spaces, no tabs)
- Avoid fully qualified type names
- Indent comment at the same line as the code
- All member variables should be declared at the top of classes; properties and methods should be separated by one line each
- Declare local variables as close as possible to the first time they're used
- File names should reflect the classes that they contain
Common Pitfalls
Let's face it, we all do these things one time or another. Let's avoid them as best as we can:
Names that make sense to no one but ourselves.
string myVar;
MyFunction();
Single or double letter variable names (this is excusable for local variables).
int a, b, c, a1, j1, i, j, k, ii, jj, kk, etc.
Abstract names.
private void DoThis();
Routine48();
string ZimboVariable;
Acronyms.
AF();
SFAT()
Different functions with similar names.
DoThis();
DoThisWillYa();
Names starting with underscores. They look cool, but let's not ;)
int _m1 = 0;
string __m2 = "";
string _TempVariable = "";
Variable names with subtle and context-less meanings.
string asterix = "";
void God()
{
...
}
Abbreviations.
string num;
int abr;
int i;
References
And Thanks
For reading this far. I am looking forward to your valuable suggestions. Take care!
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh) | FirstPrevNext |
|
|
 |
|
|
http://msdn2.microsoft.com/en-us/library/czefa0ke(vs.71).aspx[^]
You can also just follow Microsoft's standards. That way everyone working on a project can refer to the same guidelines without having to come up with your own rules that will change over time and over different projects.
I've been using this and passing it along to other .NET developers for a few years. Its pretty through and covers naming of everything listed here. Plus, it matches the conventions used in .NET framework, so its easier for other developers to understand your code (since it will look like the frameworks naming conventions, etc.).
|
| Sign In·View Thread·PermaLink | 5.00/5 (3 votes) |
|
|
|
 |
|
|
If you like that, read this[^].
"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Despite all the flames, i liked the simplicity though not completely convinced, there are developers who don't follow these basics also
Do you plan to continue with the next part of the article ? i would like to see it and don't bother your self with the votes
Omit Needless Words - Strunk, William, Jr.
Vista? Photoshop Preview Handler here
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
I use this for variables. Is it okay?
string This_Is_A_Damn_Temp_Variable_Dont_Use_It_For_Any_Other_Purpose = "";
Relax people.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
 Nope.
1) You are using PascalCasing. Use camelCasing. 2) "_" in variable names (and most other names) is bad. 3) That name is just WAY to long!

Seriously though, I do have to side with the message posters on this. Have a temp variable called "temp" is bad. Yes, it is for Temporary use, but it still violates the naming rules as you don't know what it is, just that it is temporary.
As one poster said, or local variables are "temporary" in their life, so allowing a name of temp is pointless and bad.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Syed M Hussain wrote: I use this for variables. Is it okay?
string This_Is_A_Damn_Temp_Variable_Dont_Use_It_For_Any_Other_Purpose = "";
i mentioned concise names that accurately describe the variable, method or object
Here
DamnTemp = ""; is enough
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Has anyone come up with a way of differentiating method parameters from local variables? I understand that camelCasing is the standard for both. But, I'd like a visual hint so that I can watch out for I do to parameters, particularly if they are both in's and out's.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
How about this way of using name variables with class member and method parameter to differentiate?
public class LocalVariables { private string name;
public bool GuessWho(string name) { ... if(name == this.name) return true; else return false } }
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
From what I have seen, nope. They use the same naming rules.
You could "break" the rules and do things like prefix argument names with a "a" (for argument). As long as you are consistent (all arguments in all methods are prefixed), that is the most important thing.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
- Namespaces - "Indicate your company or name, product and then your utility." This is nonsense. What if I have code that I use in several products? Which product name do I use? Or do I concatenate the product names?
- Methods with return values - "The name should reflect the return value." So why do you use "GetDimensions" instead of "GetDimension"? The method is only returning one value.
- Do not abbreviate variable names - "Good: index = 0; Bad: int i = 0;". Give me a break. How is "index" more meaningful than "i"? Moreover, later in the article you state "Single or double letter variable names [are] excusable for local variables". Not too consistent.
- Casing - You state that "C# standards dictate that you use a certain pattern of CamelCasing (first word capitalized) and pascalCasing (all but first word capitalized)." This is reversed of what it should be, and you then go on to talk about "PascalCasing" and "camelCasing".
- Indentation - "Use strict indentation (3 or 4 spaces, no tabs)". Does this mean that you allot time in all your projects to convert the Microsoft-supplied sample code from tabs to spaces? Absurd.
- spelling - You state this is your first article and you want to make a good first impression, so why didn't you spellcheck it? For something that aspires to be a "standard", it contains some glaring misspellings: bestest, privtae, stirng.
From reading your article, I would guess that you haven't spent much time trying to maintain other people's code. It's nonsense to include trivial code formatting issues in a coding standard - if you don't like the format, use Visual Studio's format command, or a 3rd party code beautifier. There have been times when I would have paid cash money for a decent comment in the middle of some dense code, but all you say about comments is to spellcheck them and line them up. There are many issues that you don't even mention, that contribute significantly to code reuse, portability and maintainability. Finally, there are tools available that check source code for compliance with company standards, and it would have been nice to see some mention of these too.
I would say that your article rating of 3+ is generous.
|
| Sign In·View Thread·PermaLink | 3.46/5 (4 votes) |
|
|
|
 |
|
|
Thanks for taking the time to go through the article
The article is for developers who don't follow any convention (beginner's ), its difficult to argue whether these are right or wrong, and code formatting is trivial or not , it depends on every individual, as we gain experience we have to decide for ourself whether we should follow some conventions or not and to what extent.
These are some methods, some standards and i am saying it had been good for me. you can try it or you can go ahead and read 50 pages of manual. It took me few hours to compile this and i also got this edited by another cpian, there might be some mistakes in the article, revisions will be there.
You can take the good things out of it or ...
John C. Turner wrote: There are many issues that you don't even mention, that contribute significantly to code reuse, portability and maintainability. Finally, there are tools available that check source code for compliance with company standards, and it would have been nice to see some mention of these too.
Send me these as a few paragraphs and i will add them here
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
What about using this to explicitly state where the method is located? i.e.
//good this.CreateBitmap(m_xSize, m_ySize) vs
//bad CreateBitmap(m_xSize, m_ySize) // where is CreateBitmap? If it sounds like a framework method, is it?
I know that it's not needed, but I like to know where the code is being called at a glance, without having to dig into the codebase.
Thoughts?
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Jamie Furtner wrote: //good this.CreateBitmap(m_xSize, m_ySize)
ofcourse it is always good convention to have it like this, the basic idea of the coding standard is to make things easier and have a convention, a standard, which should help us later. not to follow things just for the sake of it, it has to be for a reason and it should be consistent.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
Jamie Furtner wrote: //good this.CreateBitmap(m_xSize, m_ySize) vs //bad CreateBitmap(m_xSize, m_ySize) // where is CreateBitmap? If it sounds like a framework method, is it?
The problem with these types of "standards" is that the compiler does not enforce them, and making any attempt to utilise this "semantic standard" is merely lulling you into a false sense of understanding (of the code), since semantically the use of "this." does not guarantee anything like what you want it to guarantee.
In other words, although you might want to use "this." to mean you are calling a method in YOUR class, rather than a base-class, semantically "this." can be used to call any member function of the object.
In C++ (my primary language) we have a similar problem with the keyword "virtual". When overriding a virtual method in a derived class, the "virtual" keyword is optional. If you omit it, the method will still be virtual because the base-class method was virtual. I would prefer "virtual" to be repeated in the derived class since it makes it obvious this is an overriding function, but the language (hence the compiler) does not compel you to do so. (At least C# is good in that respect by having override and new keywords).
So unlike a naming standard your example is a semantic standard but it cannot be checked for correctness by the compiler itself. Because of this, it can be used erroneously, and then all it serves to do is induce a false sense of understanding in the person reading your code. I don't mind the idea, but since it is prone to error I would not bother.
Finally, if you consider future refactoring of the code, which may well separate a class into two classes (base and derived), then usage of "this." would actually hinder the refactoring process since all the former "this.SomeMethod" calls would have to be changed if the convention was to mean what was intended. Once again, the developer would need to examine these themselves, as the compiler would happily accept the code. More than likely some of these changes would be missed, and the code has now reverted to the problem I described above.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
"Variables - Do not abbreviate variable names. Variable names should again be descriptive and meaningful.
//Good int customerCount = 0; int index = 0; string temp = "";"
temp WHAT? "temp" is both abbreviated and meaningless.
"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe
|
| Sign In·View Thread·PermaLink | 3.83/5 (7 votes) |
|
|
|
 |
|
|
what did you meant ?
"temp" ofcourse is a word and it means "a worker hired on a temporary basis" and is most commonly used for temperory variables
and i am comparing "temp" with "t", does that not make any sense
|
| Sign In·View Thread·PermaLink | 3.67/5 (3 votes) |
|
|
|
 |
|
|
DeepWaters wrote: "temp" ofcourse is a word and it means "a worker hired on a temporary basis"
In this context? What part of "string temp" says it's "a worker hired on a temporary basis"?
DeepWaters wrote: is most commonly used for temperory variables
Because temp means abbreviation of temporary in this context. It says little about what is temporary here, and choosing this general name "temp" makes code more error prone - when someone maintain the code they can easily reuse variable named "temp" for different purpose and potentially introduce a bug. Choosing meaningful name make this harder.
Example
Lets say you have code like this:
string temp = customer.Name;
...
customer.Name = temp;
After months you add some code:
string temp = customer.Name;
...
if(...) { ... temp = customer.Address; customer.address = customer2.Address; customer.Address = temp; ... }
customer.Name = temp;
Do you see the problem here? Can this same happen when you choose meaningful name?
Example:
string customerName = customer.Name;
"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe
|
| Sign In·View Thread·PermaLink | 3.43/5 (7 votes) |
|
|
|
 |
|
|
dnh wrote: In this context? What part of "string temp" says it's "a worker hired on a temporary basis"?
String temp, says that the variable is for temporary purpose, its self explainatory. whats the fuss ?
|
| Sign In·View Thread·PermaLink | 3.00/5 (4 votes) |
|
|
|
 |
|
|
DeepWaters wrote: String temp, says that the variable is for temporary purpose, its self explainatory
No it's not self explanatory, it's vague. Is it temporary user name, temporary address? All local variables are for temporary purposes!
Did you understand my example? I don't think so.  Lets try again.
customer.Name = temp;
vs.
customer.Name = customerAddress;
Is it clearer now? From first you don't see immediately there is anything wrong, but second example shows clearly there is error.
"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe
|
| Sign In·View Thread·PermaLink | 1.36/5 (4 votes) |
|
|
|
 |
|
|
 |
|
|
Great answer!
"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe
|
| Sign In·View Thread·PermaLink | 2.33/5 (2 votes) |
|
|
|
 |
|
|
General News Question Answer Joke 
|