Programming tips

Nullable Types

C# developers know how to work with various value types such as so one, chat, double, bool, and int. While they are useful, all of them can't be set to null. For instance, a bool variable will only hold the values either false or true. Inserting the symbol ("?") makes it possible to assign null.

Nullable<bool> status = null;

int? i = null;
  • Establishing whether a String is Null? A  string.IsNullOrEmpty tests strings by looking for null or empty string references. The static method IsNullOrEmpty allows developers to test whether a string is empty or null. See below
if (string.IsNullOrEmpty(s))

   return "This string is null or empty.";


   return string.Format("This string is not null or empty, it equals to \"{0}\" ", s);

Using Statement

Memory allocation is as paramount as freeing memory. In C# there is a Garbage Collector which plays an important role. However, various classes in the .NET library enforce the IDisposable interface which requires manual object disposal. The code-snippet below indicates the creation of the SHAI class and subsequently disposes the object

SHA1 sha1 = SHA1.Create();


StringBuilder sb = new StringBuilder();

byte[] data = Encoding.UTF8.GetBytes(text);

byte[] hash = sha1.ComputeHash(data);

foreach (byte b in hash)


hashed = sb.ToString();


if (sha1 != null)


Utilizing the using statement once is the best option as seen below:

// Allocate

using (System.Security.Cryptography.SHA1 sha1

= System.Security.Cryptography.SHA1.Create())

//Use the sha1 to computer the hash.

//sha1 can only be used inside this code-block

//Automatically Disposed
  • Namespace Alias Qualifier The Namespace Alias Qualifier in C# allows developers to utilize the alias name as opposed to the complete namespace. This is useful because namespaces can become very long. Check out the example below:
using Excel = Microsoft.Office.Interop.Excel;

var excelapp = new Excel.Application();

excelapp.Visible = true;
  • Object Initializers When using the outdated method of initializing property values from outside the class, developers have to initialize the properties separately or write using a constructor. See the following example
Child child = new Child();

child.Age = 10;

child.Name = "Bryan";

child.StreetAddress = "Seattle, WA 98124";

This code can be written as:

Child child = new Child() { Age = 10, Name = "Bryan", StreetAddress = "Seattle, WA 98124" };

This language attribute exists in C# 3.0 and current versions.

Implementing the Base Type for a Generic Type

When developers want to enforce the generic type provided in a generic class such that it will be able to inherit from a particular interface, they can follow this sample

 class MyGenricClass<T> where T : IMyInterface

           //Body of the class come in here

   You could also do it at the method level.

   class MyGenricClass

           public void MyGenericMethod<T>(T t) where T : IMyInterface

                   //Generic implementation goes in here
  • Using Property as IEnumerable doesn’t make it Read-only When an IEnumerable property gets exposed in a created class, callers can modify as follows
  class Program

           static void Main(string[] args)

                   MyClass myClass = new MyClass();

           ((List<string>)myClass.ReadOnlyNameCollection).Add("######From Client#####");


           class MyClass

           List<string> _nameCollection = new List<string>();

       public MyClass()





       public IEnumerable<string> ReadOnlyNameCollection

       get { return _nameCollection.AsEnumerable(); }

       public void Print()

       foreach (var item in ReadOnlyNameCollection)


This code modifies the list and gives it a new name. In order to avoid this, add AsReadOnly as opposed to AsEnumerable.

       public IEnumerable<string> ReadOnlyNameCollection

       get { return _nameCollection.AsReadOnly(); }
  • Data Type Conversion More often than not, developers have to alter data types for different reasons. For example, converting a set value decimal variable to an int or Integer, the explicit conversion is done as follows.
int j = 0;

decimal money = 9500.34m;

j = (int)money; // An explicit conversion using cast operator.

Using the Convert class which supports full Data Type conversion between all data types is the best option.

int money = 0;

string uservalue = null;

uservalue = Console.ReadLine();

money = Convert.ToInt32(uservalue);

In the former code-snippet, an explicit conversion is done using a cast operator. In the latter code-snippet, the Convert class is used while the ToInt32() method is invoked to convert a string into an int. Explicit conversions require a cast operator. In addition, the destination and source variables should be compatible. Conversion with the assistance of a helper class such as Convert enables us to convert between non-compatible types. This does not need the use of a cast operator.

Making a retirement announcement

Developers who own re-distributable components and probably want to detract a method in the near future, can embellish it with the outdated feature to connect it with the clients. Check out the following C# sample code [Obsolete("This method will be deprecated soon. You could use XYZ alternatively.")]

       public void MyComponentLegacyMethod()

           //Here is the implementation

Upon compilation, a client gets a warning upon with the message. To fail a client build that is using the detracted method, pass the additional Boolean parameter as True. [Obsolete("This method is deprecated. You could use XYZ alternatively.", true)]

       public void MyComponentLegacyMethod()

           //Here is the implementation
  • Deferred Execution While Writing LINQ Queries When a LINQ query is written in .NET, it can only perform the query when the LINQ result is approached. The occurrence of LINQ is known as deferred execution. Developers should understand that in every result set approach, the query gets executed over and over. In order to prevent a repetition of the execution, change the LINQ result to List after execution. Below is an example public void MyComponentLegacyMethod(List<int> masterCollection)
  //Without the ToList this linq query will be executed twice because of the following usage

           var result = masterCollection.Where(i => i > 100).ToList();


  • Explicit keyword conversions for business entities Utilize the explicit keyword to describe the alteration of one business entity to another. The alteration method is conjured once the alteration is applied in code. Below is an example.
class Program

       static void Main(string[] args)

           ExternalEntity entity = new ExternalEntity()

               Id = 1001,

               FirstName = "Dave",

               LastName = "Johnson"


           MyEntity convertedEntity = (MyEntity)entity;

    class MyEntity

       public int Id { get; set; }

       public string FullName { get; set; }

        public static explicit operator MyEntity(ExternalEntity externalEntity)

                 return new MyEntity()

                           Id = externalEntity.Id,

               FullName = externalEntity.FirstName + " " + externalEntity.LastName

   class ExternalEntity

    public int Id { get; set; }

       public string FirstName { get; set; }

       public string LastName { get; set; }
  • Absorbing the Exact Stack Trace In the catch block of a C# program, if an exception is thrown as shown below and probably a fault has occurred in the method ConnectDatabase, the thrown exception stack trace only indicates the fault has happened in the method RunDataOperation. This means that the exact error source will have been lost as seen below.
  public void RunDataOperation()




               Execute ();

            catch (Exception exception)

              throw exception;

      Preserve the exact stack trace throw as seen below

       public void RunDataOperation()





                       catch (Exception)

  • Enum Flags Attribute Using flags attribute to decorate the enum in C# enables it as bit fields. This enables developers to collect the enum values. One can use the following C# code.
   class Program

       static void Main(string[] args)

           int snakes = 14;



   enum Reptile

       BlackMamba = 2,

       CottonMouth = 4,

       Wiper = 8,

       Crocodile = 16,

       Aligator = 32

The output for this code will be “BlackMamba, CottonMouth, Wiper”. When the flags attribute is removed, the output will remain 14.


Many developers build a POCO class in order to return multiple values from a method. Tuples are initiated in .NET Framework 4.0. They can be used effectively as follows

public Tuple < int, string, string > GetEmployee()

int employeeId = 1001;

string firstName = "Rudy";

string lastName = "Koertson";

//Create a tuple and return

return Tuple.Create(employeeId, firstName, lastName);
  • Do not bother with Temporary Collections, Use Yield instead A temporary list that holds salvaged and returned items may be created when developers want to pick items from a collection. When using a temporary list, use this C# code.
public List < int > GetValuesGreaterThan100(List < int > masterCollection)

List < int > tempResult = new List < int > ();

foreach(var value in masterCollection)

if (value > 100)

 temp result.Add(value);

return temp result;

In order to prevent the temporary collection from being used, developers can use yield. Yield gives out results according to the result set enumeration. When using yield, use this code

public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection)

           foreach (var value in masterCollection)

               if (value > 100)

                   yield return value;

Developers also have the option of using LINQ.

Write Unit Test for Non-Public Methods

Many developers do not write unit test methods for non-public assemblies. This is because they are invisible to the test project. C# enables one to enhance visibility between the assembly internals and other assemblies. The trick is to include //Make the internals visible to the test assembly [assembly: InternalsVisibleTo("MyTestAssembly")] in the AssemblyInfo.cs file.

Combine Assignment With a Function Call

In C++, you can combine an assignment and a function call. Instead of this:

int i;i = 10;printf("%d", i); // prints 10

You can do this to save some code lines:

int i;printf("%d", i = 10); // prints 10

Pre-Increment Is Faster Than Post-Increment

In C++, there are two operators that can be used to increment a value by 1:

  • Pre-increment, ++i — Before assigning the value to the variable, the value is incremented by one.
  • Post-increment, i++ — After assigning the value to the variable, the value is incremented. As a result, pre-increment, ++i, is faster than post-increment because post-increment keeps a copy of the previous value where pre-increment directly adds 1 without copying the previous value.

The --> Operator

You can use the --> “operator” in a while loop as a “Goes to” operator. For example, you can print numbers 9 8 7 6 5 4 3 2 1 with a while loop like this:

int x = 10;while( x --> 0 ) {     printf("%d ", x);}

Note: --> is actually not an operator, but rather a combination of two operators, -- and >. The above while is the same as while( (x--) > 0 ), which reads “decrement x by 1 and then compare the result with 0.”

Swap Two Variables Without the Third

You can use the XOR operator to swap two variables without using a third helper variable. Here’s an example:

int a = 1;int b = 2; a ^= b ^= a ^= b;