BEST PRACTICE

Returns
1. NULL Returns
– When returning a collection or enumerable ALWAYS return an empty enumerable/collection

String
1. String Concatenation
– Use StringBuilder instead of String concatenation
– string concatenation creates new memory allocation for new string
– stringBuilder uses the same memory
2. Always use string.IsNullOrEmpty() and string.IsNullOrWhiteSpace() whenever possible

LINQ
1. WHERE() with FIRST()
– Avoid using WHERE and First together or First when you are unsure that the result can be null.
– Use FirstOrDefault() where ever possible

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {       
            //INCORRECT
            List numbers = new List{1,4,5,8,11,14,20,21,25,34,40};
            int firstEven = numbers.Where(x => x % 2 == 0).First();
            Console.WriteLine("First Even number : {0}", firstEven);
            
            //CORRECT
            int firstEvenCorrect = numbers.FirstOrDefault(x => x % 2 == 0);
            Console.WriteLine("First Even number : {0}", firstEvenCorrect);
        }
    }
}

Casting
1. Cast by “as (T)” instead of “(T)”

As (T) (T)
Returns null when casting is not possible Prefix casting will throw exception
Can be applied to reference type variable only Prefix is free for all
Cannot perform user-defined conversions Prefix can perform User defined conversion
//INCORRECT
var dog = (Dog)animal;

//CORRECT
var dog = animal as Dog;

Exceptions
1. Re-throwing exceptions

//INCORRECT 
throw ex;

//CORRECT
throw;

Enumerations
1. Use FOR LOOP for non collection eg array
2. Use FOR EACH for collection
3. Do not use OrderBy before Where clause

Keywords
1. Avoid using “ref” and “out” keywords as much as possible

Class
1. Always use properties instead of public variables

Leave a Reply

Your email address will not be published. Required fields are marked *