Home > .NET > Some C# Coding Guidelines

Some C# Coding Guidelines

My goal is to add more to this in the future, but this is a very good start. I need to remember most of these myself. Sources are linked below.

> Properties (get, set blocks) and enums should be placed after all the methods have been defined at the end of the class.

> If possible, try to maintain methods in alphabetical order to ease finding certain methods.

> Use names that describe a type’s meaning rather than names that describe the type

> One declaration per line is recommended since it encourages commenting. In other words,

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.

> Do NOT use “+” sign to concatenate strings. It creates three instances of string. Try doing that in a long or infinite loop and your program will die with an OutOfMemory exception. Instead, use string.Concat as it uses only one instance. If you are concatenating many strings in a loop, then use StringBuilder.

> If using Generic types, do not use the “foreach” loop on the collection. Instead, you should use the ForEach method to loop through via an anonymous method predicate. This will perform much faster because it doesn’t create the Iterator. For non generic types try to use “for loop” instead of foreach if the data being traversed is large.


List<string> list = new List<string>();
list.Add("aa");
list.Add("bb");

//option 1:
foreach(string str in list) {
Console.WriteLine(str);
}

//option 2: RECOMMENDED
list.ForEach(delegate(string str) {
Console.WriteLine(str);
});

> Rather than using an IF condition when there is only one item in each branch, you should use the ternary operator.

Instead of:

if (b > c) {
a = b;
} else {
a = c;
}

It is better to write:

a = (b > c) ? b : c;

> Always do NULL checking before operating on an object. Your code should never have a NullReferenceException. Period.

> By typing /// on the line before a method, Visual Studio will automatically create summary, param, and return tags. This should be done after the parameters and return value has been declared so that the editor will pick them up. The name of the method should be added to the top of this block to ease finding certain methods in larger classes.

// SomeMethod
///
/// <summary>
/// This is some method that does something
/// and I hope this description will make
/// sense to someone other then me.
/// </summary>
/// <param name="parm1">The is the first parameter.</param>
/// <return>This returns some value for some reason</return>
private int SomeMethod(string param1)
{
// good comments throughout
}

> Do not return an internal instance of an array. This allows calling code to change the array. The following example demonstrates how the array badChars can be changed by any code that accesses the Path property even though the property does not implement the set accessor.

using System;
using System.Collections;

public class ExampleClass
{
public sealed class Path
{
private Path(){}
private static char[] badChars = {'\"', '<', '>'};
public static char[] GetInvalidPathChars()
{
return badChars;
}
}
public static void Main()
{
// The following code displays the elements of the
// array as expected.
foreach(char c in Path.GetInvalidPathChars())
{
Console.Write(c);
}
Console.WriteLine();

// The following code sets all the values to A.
Path.GetInvalidPathChars()[0] = 'A';
Path.GetInvalidPathChars()[1] = 'A';
Path.GetInvalidPathChars()[2] = 'A';

// The following code displays the elements of the array to the
// console. Note that the values have changed.
foreach(char c in Path.GetInvalidPathChars())
{
Console.Write(c);
}
}
}

Sources:
Sumit Amar, MSFT : Basic C# coding guidelines
Eric Gunnerson

kick it on DotNetKicks.com

Advertisements
Categories: .NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: