C# – Framework Design Guidelines

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

C# Error: Sequence contains no element

C# Error: Sequence contains no element

This error happen when I was trying to call Single() command like this:
Held holdData = new HeldBusinessLogic().Get(id: cId).Single();

Since there was no record in the Held table, the Single() command results in error: “Sequence contains no elements”

To fix the issue I had to change the code to:
Held holdData = new HeldBusinessLogic().Get(id: cId).FirstOrDefault();

The FirstOrDefault() returns null when there is no record whereas Single() tries to retrieve an element from the sequence

This error can also result when you attempt to execute any aggregate method on an empty result set.

Example
int maxData = context.Surface.Max(s => s.Surface.GetValueOrDefault());

To fix this:
int maxData = context.Surface==null?0: context.Surface.Max(s => s.Surface.GetValueOrDefault());

Another Filter example

Error
claim.Held.First(c => c.ClaimId == claimId);
Solution
claim.Held.FirstOrDefault(c => c.ClaimId == claimId);

However this can happen with the following commands also:
First() – use first when you know the sequence will have at least one element
FirstAsync() – Asynchronously returns the first element of a sequence.
SingleAsync() – Asynchronously returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
Last() – Returns the last element of a sequence.
LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.
LastAsync()