Programming Practices

Contents

File Paths

In general, avoid paths in source code. When adding two paths do NOT concatenate them with the + operator, instead use the Path.Combine method.

Do not use:

string path = root + "\\subdir";

Use:

string path = Path.Combine(root, "subdir");

If you must use backslashes in code, use @-quoted string literals.

Do not use:

"subdir\\subsubdir";

Use:

@"subdir\subsubdir";

Creating a project

When creating a new project you must not copy an existing one. E.g. it's the csproj file that should not be duplicated as this file contains a unique project identifier. If a whole project is copied including this file you will end up with two different features with the same identifier.

 

Performance Tips

Local variables

Avoid method implementations that contain more than 64 local variables. (Of course shorter methods and fewer variables are preferred!)
In order for the run-time to register local variables efficiently, there should be max 64 variables. Registering based on flow analysis will not occur for locals in excess of 64, which may result in slower performance.

 

Array properties with Clone

Do not call properties that clone values while inside a loop. (And avoid creating array properties which clones values.)

public class Box 
{ 
    private ArrayList m_items;    
    public Box(ArrayList items) { m_items = items; } 
    public ArrayList Items { return m_items.Clone(); } 
} 

Bad:

for (int i = 0; i < myBox.Items.Length; i++) 
{
    Console.WriteLine(myBox.Items[i]); 
}

Good:

ArrayList myItems = myBox.Items; 
for (int i = 0; i < mytems.Length; i++) 
{
    Console.WriteLine(myItems[i]); 
}

 

String concat inside loops

Consider not calling String.Concat inside loops (since strings are immutable and a new string object will be allocated for every iteration). Using the StringBuilder class gives better performance.

Bad:

string result = String.Empty; 
for (int i = 0; i < 1; i++) 
{ 
    result = result + token[i]; 
} 

Good:

StringBuilder sb = new StringBuilder(); 
for (int i = 0; i < 1; i++) 
{ 
    sb.Append(token[i]); 
} 
string result = sb.ToString(); 

 

Static constructors

Do not declare explicit static constructors

Static fields should be initialized when declared. For reference types, initializing static data in explicit static constructors results in less performant code. For value types, this can also be a code correctness issue since, in some cases, the existence of an explicit static constructor on a value type will prevent its guaranteed execution before fields on the value type are accessed.

Bad:

class Foo 
{ 
    static int bar; 
    static Foo() { bar = 7; } 
} 

Good:

class Foo
{
    
    static int bar = 7;
}