.NET Daily

C#

C# Coding Standards Series – Language Usage

Posted on .

C# Coding Standards Series – Language Usage

Introduction

This post is part of a series that covers most of notable C# coding standards that you should follow.

You can download the document with all of the post from here: [download id=”2″ format=”1″]

You can see here the other posts within the series.


In .NET, if you don’t respect some basic rules about language usage you can end up by spending a lot of time on debugging code and trace bugs caused by inadvertently written code.

1. General Rules

1.1 Do not omit access modifiers. Explicitly declare all identifiers with the appropriate access modifier instead of allowing them by default:
Ex:

Good:

Bad:

1.2 Only declare member variables as private. Use properties to provide access to them with public, protected or internal access modifiers;

1.3 Convert strings to lower case or upper case before comparing. This will ensure the string will match even if the string compared has a different case:

Ex:

1.4 Use String.Empty instead of ” “:

Ex:

Good:

Bad:

1.5 Try to use int for any non-fractional numeric values that will fit into int data type, even for negative numeric values;

1.6 Only use long for variables potentially containing values too large for int data type;

1.7 Use double for fractional numbers to insure decimal precisions in calcultations;

1.8 Use float for fractional number that will not fit in decimal or double. Still avoid using float unless you fully understand the implications upon any calculations;

1.9 Use String.Builder instead of string when you have to manipulate string objects in a loop;

1.10 Try to use “@” prefix for string literals instead of escaped strings;

1.11 Avoid using ternary conditional operator. For complex operations can be difficult to understand:

Ex:
int result = isValid ? 9 : 4;

3.1.12 Avoid evaluating Boolean conditions against true or false:
Ex:
Good:

Bad:

1.13 Use switch/case statements for simple operations with parallel conditional logic;

1.14 Prefer nested if/else over switch/case for short conditional sequences and complex conditions;

1.15 Prefer polymorphism over switch/case to encapsulate and delegate complex operations;

Please share your opinion about this post by commenting below.

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

There are no comments.

View Comments (0) ...
Navigation