5,427,303 members and growing! (15,188 online)
Email Password   helpLost your password?
Languages » C# » Beginners     Beginner License: The GNU General Public License (GPL)

C# Coding Practicies Guide

By Chesnokov Yuriy

The article describing C# coding style and practices to be followed to develop robust and reliable code easily comprehended and maintained by other developers
C# (C# 1.0, C# 2.0, C# 3.0, C#)

Posted: 20 Jun 2008
Updated: 20 Jun 2008
Views: 3,490
Bookmarked: 11 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
19 votes for this Article.
Popularity: 2.31 Rating: 1.80 out of 5
12 votes, 63.2%
1
4 votes, 21.1%
2
1 vote, 5.3%
3
0 votes, 0.0%
4
2 votes, 10.5%
5
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

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 with compared to C++ (as VS provides you even automatic indentation and code formating) 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:

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, 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 there will be the same tool for C++ language.

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:

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:

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

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

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

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

Use override instead of new

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

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

License

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

About the Author

Chesnokov Yuriy


Mvp
Former Cambridge University post-doc (http://www-ucc.ch.cam.ac.uk/research/yc274-research.html) currently lives in Krasnodar, Russia and doing some contract research for third parties. Research intrests in digital signal processing in medicine, image and video processing, pattern recognition, AI methods, computer vision. You may approach me for the code/research development in the above areas (chesnokov_yuriy at mail dot ru, chesnokov.yuriy at gmail dot com).

Publications:

Complexity and spectral analysis of the heart rate variability dynamics for distant prediction of paroxysmal atrial fibrillation with artificial intelligence methods. Artificial Intelligence in Medicine. 2008. V43/2. PP. 151-165 (http://dx.doi.org/10.1016/j.artmed.2008.03.009)

Face Detection C++ Library with Skin and Motion Analysis. Biometrics AIA 2007 TTS. 22 November 2007, Moscow, Russia. (http://www.dancom.ru/rus/AIA/2007TTS/ProgramAIA2007TTS.html)

Screening Patients with Paroxysmal Atrial Fibrillation (PAF) from Non-PAF Heart Rhythm Using HRV Data Analysis. Computers in Cardiology 2007. V. 34. PP. 459–463 (http://www.cinc.org/Proceedings/2007/pdf/0459.pdf)

Distant Prediction of Paroxysmal Atrial Fibrillation Using HRV Data Analysis. Computers in Cardiology 2007. V. 34. PP. 455-459 (http://www.cinc.org/Proceedings/2007/pdf/0455.pdf)

Individually Adaptable Automatic QT Detector. Computers in Cardiology 2006. V. 33. PP. 337-341 http://www.cinc.org/Proceedings/2006/pdf/0337.pdf)


Past/recent outsourcing code/research:

confidential Japanese company - face recognition C/MATLAB
confidential company in Australia - video capture C#/DirectShow
www.system7.co.uk - CBIR C#/ASP.NET (cbir.system7.com)
confidential enterprise in UK - pedestrian detection C++/CLI
www.trulyintelligent.com - SpeechSieve consulting in AI
www.devline.ru - video codecs C++
Occupation: Software Developer
Company: Confidential Japanese firm (face recognition)
Location: Russian Federation Russian Federation

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralBest Practicesmemberthund3rstruck6:01 23 Jun '08  
GeneralCoding Standards link (cyber squatter page)memberTodd Smith9:16 20 Jun '08  
GeneralMicrosoft's guidlines include what you've written and more..memberSeishin#5:52 20 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Jun 2008
Editor:
Copyright 2008 by Chesnokov Yuriy
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project