Seitenhierarchie

  Wiki Navigation

    Loading...


 Recently Updated


 Latest Releases

 MediaPortal 1.32
            Releasenews | Download
 MediaPortal 2.5
            Releasenews | Download



On 27 Sep 2010, chefkoch suggested that this page or content is incomplete and needs to be expanded with information on using Visual Studio and ReSharper templates with links to these.

IMPORTANT: Header

As we are an open source project every file in SVN needs the copyright header. Please copy that header paragraph to the beginning of each document. You can copy the current header from another file in MediaPortal 1/ MediaPortal 2 and you find it in the templates in the MediaPortal 2 source tree.

The header looks like this (most probably with a newer year as typically our devs forget to change this wiki page):

Sample of a C# file header:

#region Copyright (C) 2005-2010 Team MediaPortal

// Copyright (C) 2005-2010 Team MediaPortal
// https://www.team-mediaportal.com
// 
// MediaPortal is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// MediaPortal is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with MediaPortal. If not, see <http://www.gnu.org/licenses/>.

#endregion
#region Copyright (C) 2007-2010 Team MediaPortal

/*
    Copyright (C) 2007-2010 Team MediaPortal
    https://www.team-mediaportal.com

    This file is part of MediaPortal 2

    MediaPortal 2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MediaPortal 2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MediaPortal 2.  If not, see <http://www.gnu.org/licenses/>.
*/

#endregion

C# source

Keep your classes/files short, don't exceed 2000 LOC, divide your code up, make structures clearer. Put every class in a separate file and name the file like the class name (with .cs as extension of course). This convention makes things much easier.

IMPORTANT: Indentation

  • Use .editorconfig file :

This feature work natively on Visual Studio only since Visual Studio 2017, else an plugin is available on https://github.com/editorconfig/editorconfig-visualstudio for Visual Studio 2012, 2013, and 2015. 

Does not support insert_final_newline and trim_trailing_whitespace (note that these options are supported from Visual Studio 2017 version 15.3)

What is Editorconfig ?

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs. The EditorConfig project consists of a file format for defining coding styles and a collection of text editor plugins that enable editors to read the file format and adhere to defined styles. EditorConfig files are easily readable and they work nicely with version control systems.

Editorconfig website url

.Editorconfig parameter defined : 

; Top-most EditorConfig file
root = true

; Unix-style newlines
[*]
end_of_line = crlf

; 2-column space indentation
[*.cs]
indent_style = space
indent_size = 2
tab_width = 2
trim_trailing_whitespace = true

Project enable to use .editorconfig file :

Mediaportal 1 - Client (not TVE)

MPTVClient


Auto Formating in Visual Studio via Edit (Menu) -> Advanced -> Format Document or by Shortcu  Ctrl+K followed by Ctrl+D

If .editorconfig is enable, you don't need to modify your Visual Studio setting as mentionned below.


  • Set Visual Studio where .editorconfig is not enable :

Setup Visual Studio to use 2 spaces as indentation and use Automatic Formatting regularly

In Microsoft Visual Studio this can be set via Tools (Menu) -> Options -> Text Editor -> C# -> Tabs

(tab size = 2, indent size = 2, Insert spaces)

In VS Express this can be set via Tools (Menu) -> Options -> Text Editor -> C# -> Tabs

(tab size = 2, indent size = 2, Insert spaces)

Make sure the Show all settings box is checked.

Auto Formating in both VS 2005 and Express is done via Edit (Menu) -> Advanced -> Format Document or by Shortcu  Ctrl+K followed by Ctrl+D

Code Comments

There is an own Wiki entry describing the way of documenting the code.

Declarations

One declaration per line is recommended since it encourages commenting.

int level; // indentation level
int size; // size of table

Do not put more than one variable or variables of different types on the same line when declaring them.

Example:

int a, b; //What is 'a'? What does 'b' stand for?

The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.

Class and Interface Declarations

When coding C# classes and interfaces, the following formatting rules should be followed:

  • No space between a method name and the parenthesis " (" starting its parameter list.
  • The opening brace "{" appears in the next line after the declaration statement
  • The closing brace "}" starts a line by itself indented to match its corresponding opening brace.

Example:

Class MySample : MyClass, IMyInterface
{
  int _myInt;
  public MySample(int myInt)
  {
    _myInt = myInt;
  }
  void Inc()
  {
    ++_myInt;
  }
  void EmptyMethod()
  {
  }
}

For a brace placement example look at section 10.1.

The order of regions inside a class should be:

public class Template_Class
{
  #region Imports
  #endregion

  #region Enums
  #endregion

  #region Delegates
  #endregion

  #region Events
  #endregion

  #region Variables
  // Private Variables
  // Protected Variables
  // Public Variables
  #endregion

  #region Constructors/Destructors
  #endregion

  #region Public properties
  // Public properties
  #endregion

  #region Public methods
  #endregion

  #region Private methods
  #endregion

  #region Base overrides
  #endregion

  #region Interface implementations
  // region for each interface
  #endregion
}

This Regions layout is included in a Visual Studio code snippet that is helpfully attached here: Regions-outline.snippet

If, if-else, if else-if else Statements

if (condition)
{
  DoSomething();
  ...
}
if (condition)
{
  DoSomething();
  ...
}
else
{
  DoSomethingOther();
  ...
}
if (condition)
{
  DoSomething();
  ...
}
else if (condition)
{
  DoSomethingOther();
  ...
}
else
{
  DoSomethingOtherAgain();
  ...
}

For / Foreach Statements

A for statement should have following form:

for (int i = 0; i < 5; ++i)
{
  ...
}

or single lined (consider using a while statement instead):

for (initialization; condition; update);

A foreach should look like:

foreach (int i in IntList)
{
  ...
}

While/do-while Statements

A while statement should be written as follows:

while (condition)
{
  ...
}

An empty while should have the following form:

while (condition);

A do-while statement should have the following form:

do
{
  ...
} while (condition);

Switch Statements

switch (condition)
{
  case A:
  ...
  break;
  case B:
  ...
  break;
  default:
  ...
  break;
}

Try-catch Statements

A try-catch statement should follow this form:

try
{
  ...
} catch (Exception)
{
  ...
}
finally
{
  ...
}

White space

Blank Lines

Blank lines improve readability. They set off blocks of code which are in themselves logically related. Two blank lines should always be used between:

  • Logical sections of a source file
  • Class and interface definitions (try one class/interface per file to prevent this case) One blank line should always be used between:
  • Methods
  • Properties
  • Local variables in a method and its first statement
  • Logical sections inside a method to improve readability

Inter-term spacing

There should be a single space after a comma or a semicolon, for example:

TestMethod(a, b, c);

Do NOT use:

TestMethod(a,b,c)

Single spaces surround operators (except unary operators like increment or logical not), example:

a = b; // don't use a=b;
for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i)
// or
// for(int i=0;i<10;++i)

Naming Conventions

Capitalization Styles

Pascal Casing

This convention capitalizes the first character of each word (as in TestCounter).

Camel Casing

This convention capitalizes the first character of each word except the first one. E.g. testCounter.

Upper case

Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use Pascal casing instead. For Example:

public class Math
{
  public const PI = ...
  public const E = ...
  public const FeigenBaumNumber = ...
}

Naming Guidelines

Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation are considered bad practice.

Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. This style of naming was widely used in early Windows programming, but now is obsolete or at least should be considered deprecated. Using Hungarian notation is not allowed if you follow this guide.

A good variable name describes the semantic not the type.

An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button should be postfixed with their type name without abbreviations. For example:

System.Windows.Forms.Button cancelButton;
System.Windows.Forms.TextBox nameTextBox;

Class Naming Guidelines

  • Class names must be nouns or noun phrases
  • Use Pascal casing
  • Do not use any class prefix

Interface Naming Guidelines

  • Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
  • Use Pascal casing
  • Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)

Enum Naming Guidelines

  • Use Pascal casing for enum value names and enum type names
  • Don't prefix (or suffix) a enum type or enum values
  • Use singular names for enums
  • Use plural name for bit fields.

ReadOnly and Const Field Names

  • Name static fields with nouns, noun phrases or abbreviations for nouns
  • Use Pascal casing

Parameter/non const field Names

  • Do use descriptive names, which should be enough to determine the variable meaning and it's type. But prefer a name that's based on the parameter's meaning.
  • Use Camel casing
  • Field names always start with the prefix "_"

Variable Names

  • Counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops. (see 10.2 for an example on more intelligent naming for global counters etc.)
  • Use Camel casing

Method Names

  • Name methods with verbs or verb phrases.
  • Use Pascal casing

Property Names

  • Name properties using nouns or noun phrases
  • Use Pascal casing
  • Consider naming a property with the same name as its type.

Event Names

  • Name event handlers with the EventHandler suffix.
  • Use two parameters named sender and e
  • Use Pascal casing
  • Name event argument classes with the EventArgs suffix.
  • Name event names that have a concept of pre and post using the present and past tense.
  • Consider naming events using a verb.

Capitalization summary

Type

Case

Notes

Class / Struct

Pascal Casing

-

Interface

Pascal Casing

Starts with I

Enum values

Pascal Casing

-

Enum type

Pascal Casing

-

Events

Pascal Casing

-

Exception class

Pascal Casing

Ends with Exception

public Fields

Pascal Casing

-

Methods

Pascal Casing

-

Namespace

Pascal Casing

-

Property

Pascal Casing

-

Protected Fields

camel Casing

-

private Fields

camel Casing

-

Parameters

camel Casing

-

Programming Practices

Visibility

Do not make any instance or class variable public, make them private. For private members prefer not using private as modifier just do write nothing. Private is the default case and every C# programmer should be aware of it.

Use properties instead. You may use public static fields (or const) as an exception to this rule, but it should not be the rule.

No 'magic' Numbers

Don't use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded into your code in 50 lines scattered throughout your 25000 LOC) is error-prone and unproductive. Instead declare a const variable which contains the number :

public class MyMath
{
  public const double PI = 3.14159...
}

Brace code example

namespace ShowMeTheBracket
{
  public enum Test
  {
    TestMe,
    TestYou
  }

  public class TestMeClass
  {
    Test _test;
    public Test Test
    {
      get
      {
        return _test;
      }
      set
      {
        _test = value;
      }
    }

    void DoSomething()
    {
      if (_test == Test.TestMe)
      {
        //...stuff gets done
      }
      else
      {
        //...other stuff gets done
      }
    }
  }
}

Variable naming example

for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate)
{
  isPrime[primeCandidate] = true;
}

for (int factor = 2; factor < num / 2; ++factor)
{
  int factorableNumber = factor + factor;
  while (factorableNumber <= num)
  {
    isPrime[factorableNumber] = false;
    factorableNumber += factor;
  }
}

for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate)
{
  if (isPrime[primeCandidate])
  {
    Console.WriteLine(primeCandidate + " is prime.");
  }
}

References

Design Guidelines for Class Library Developers

   

 

This page has no comments.