Click here to Skip to main content
15,881,862 members
Articles / Programming Languages / C#

C# Coding Practicies Guide

Rate me:
Please Sign up or sign in to vote.
2.27/5 (26 votes)
20 Jun 2008GPL32 min read 43K   34   4
The article describing C# coding style and practices to be followed to develop robust and reliable code easily comprehended and maintained by other developers

Introduction

Writing consistent code comprehended by other developers is supposed to follow some coding style and practices, rather than inventing your own ones. These include naming conventions on how you name your variables and functions, code and class layout including tabs, whitespace, brackets placement, etc... Though C# is much easier to develop code when compared to C++ (as VS provides you even automatic indentation and code formatting), there are some quick guidelines you should follow. There are also some great online resources you may use in addition to that article:

Value and Reference Semantics

Compared to C++, in C# there is inherent value and reference semantics. As there are no pointers in safe code and everything is accessed with '.', there are value and reference types:

  • Value types - struct, enum, integrals, char, float, double, decimal
  • Reference types - class, string, interface, arrays, delegates

So having initialization of a value or reference type, you get different results:

C#
SomeStruct ss = new SomeStruct();
SomeClass sc = new SomeClass();
SomeStruct ss1 = ss;  //you will have new ss1 object created
SomeClass sc1 = sc;   //you get sc reference in sc1!!!

Spaces, Braces, Tabs, Code Layout

No need to worry about these, VS will do all formatting for you automatically like the one snippet below, so you are prevented from incorrectly layouting your code. Very nice feature for C#, hope the same tool will be available for C++ language.

C#
public int SaveDictionary(String fileName)
{
        try
        {
                using (StreamWriter sw = new StreamWriter(fileName))
                {
                        foreach (String word in this.stats.Keys)
                        {
                                sw.WriteLine(word);
                                List<WordFreqPair> wfpList = this.stats[word];
                                for (int i = 0; i < wfpList.Count; i++)
                                        sw.WriteLine(String.Format("    {0,-25} {1}", 
					wfpList[i].Word, wfpList[i].Prob));
                                sw.WriteLine("");
                        }                        
                }
                return 0;
        }
        catch (Exception e)
        {
                Trace.WriteLine(String.Format("TextStatistics.SaveDictionary({0}) 
			raised exception {1}", fileName, e.Message));
                this.error = String.Format("TextStatistics.SaveDictionary({0}) 
			raised exception {1}", fileName, e.Message);
                return -1;
        }
}

Naming Conventions

.NET standards do not recommend using Hungarian prefixes, so avoid them. To refer to member field inside class member function, use this word this.memberVariable. You use lower case for variables and function parameters, all the rest go with capitals:

C#
SomeClass { ... };
SomeEnum { Item1, Item2, ... };
SomeProperty { get; set }
double someVariable;
int someFunctionParameter;
const char SomeConstantVariable;
static readonly SomeReadOnlyStaticVariable;
Exception SomeNameException;
Attribute SomeNameAttribute;
Button cancelButton;
TextBox nameTextBox;
PictureBox namePictureBox;

Class Layout

It is recommended to declare class internals in that order:

  • Fields
  • Constructors
  • Nested enums, structs, classes
  • Properties
  • Methods

Miscellaneous

One class per source file (SomeName class should be declared in somename.cs file).

Private members are private by default in class, avoid explicit private.

For a single statement get/set property use that construction:

C#
public int Foo
{
        get { return this.foo; }
        set { this.foo = value; }
}

Use {} for if, else, for, while even if single lined.

C#
if (someVar == true)
{
        foo++;
}

Use @ instead of escape sequencies in strings - @"c:\somepath\file.txt"

Use override instead of new:

C#
class SomeParent
{
        //...
        public int DoWork();
        //...
}

class SomeOverride
{
        //...
        public override int DoWork();
        //...
}

Initialize string to String.Empty rather than assigning it "".

Use StringBuilder for composing complex strings rather than using string class operators.

Document if the method returns copy of reference type.

Do not compare to true or false use if(condition).

Provide private constructor if only static fields are in the class or declare static class.

Const objects in class are static by default.

Struct may have constructor with parameters only.

Consider documenting your code so you will not be trying to recall what the method is supposed to do after some days have gone.

C#
/// <summary>
/// Save trimmed text
/// </summary>
/// <param name="fileName">Trimmed text file name</param>
/// <returns>zero upon success</returns>
public int SaveText(String fileName)
{
//...
}

History

  • 20th June, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Engineer
Russian Federation Russian Federation
Highly skilled Engineer with 14 years of experience in academia, R&D and commercial product development supporting full software life-cycle from idea to implementation and further support. During my academic career I was able to succeed in MIT Computers in Cardiology 2006 international challenge, as a R&D and SW engineer gain CodeProject MVP, find algorithmic solutions to quickly resolve tough customer problems to pass product requirements in tight deadlines. My key areas of expertise involve Object-Oriented
Analysis and Design OOAD, OOP, machine learning, natural language processing, face recognition, computer vision and image processing, wavelet analysis, digital signal processing in cardiology.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Espen Harlinn3-Jul-11 5:50
professionalEspen Harlinn3-Jul-11 5:50 
GeneralBest Practices Pin
thund3rstruck23-Jun-08 5:01
thund3rstruck23-Jun-08 5:01 
GeneralCoding Standards link (cyber squatter page) Pin
Todd Smith20-Jun-08 8:16
Todd Smith20-Jun-08 8:16 
GeneralMicrosoft's guidlines include what you've written and more.. Pin
Seishin#20-Jun-08 4:52
Seishin#20-Jun-08 4:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.