Little Coding Tricks

In this article we will learn little tricks in coding that will make our development faster and our code better.


There are instances when we need to check if a particular string is equal to another string and this is what we usually write in our code:

 if (string1==string2)


        //do stuff here


    if (string.Compare(string1.Trim(), string2.Trim(), true))

    // the last parameter decides if you want to compare case or not.


        // do stuff here


Also remember 
to trim your strings before comparison as there are instances where the user 
enters data with a space at the end or beginning and it takes a long to find out 
that the space in the string was the culprit for comparison. Please also look at 
String.Equals() docmentation.

using Statements

How many times 
have we used made that mess at the dining table and left that empty plates to be 
picked up by the maid, only if you could have picked up that plate and kept it 
in the kitchen yourself that would save the maids time to put that in the 
garbage bag outside. Thank goodness we have using statement to help us while 
writing our code, it ensures that the object is disposed upon its use and you do 
not need worry about that any more.
Example : 

using (Font font3 = new Font("Verdana", 7.0f),font4 = new Font("Calibri", 8.0f)){

// Use font3 and font4.}

In the above example we when the code execution crosses the end braces the instance of object font3 and font4 are disposed.

Have you ever thought what will happen in the case below, why don't you try this and figure out yourself? Font font2 = new Font("Verdana", 7.0f);

using (font2) // not recommended, but still let's do it

    { // use font2


float f = font2.GetHeight(); // what will happen here?


Case 1 : Or what will happen in the below cases :
(Font font3 = new Font("Verdana", 7.0f))
{throw new Exception("This is the exception");}

Case 2 :

using (Font font3 = new Font("Verdana", 7.0f)){


Is font3 still alive in both the above cases ?

If you do not have any additional logic involved in your property declaration you can take advantage of the auto
implementation of the properties.
Example :

class Employee


//Auto Properties for get and set    

public double TotalSalary {get; set; }

public string EmpName {get; set; }

public int EmpID {get; set; }

    // Constructor      

    public Employee(double totalSalary, string empName, int empID)


         TotalSalary = totalSalary;

         EmpName = empName; EmpID = empID;    }

    // .. methods, etc. }



Here we see that there is no need to create a private variable for our property as well as assigning the value, this will
be done automatically by the compiler.
There are instances in our code where we need to check if the string is null/nothing or its value is blank/empty, what

we usually write is :

if (mystring == null || mystring == String.Empty){
// code here}

We can use the above method and have much cleaner code like the one below:

 if (String.IsNullOrEmpty(mystring))


 // code here



But if your string contains a white space like this mystring= " " than the String.IsNullOrEmpty method will give you
False, so in this case we should use string.IsNullOrWhiteSpace. Normally we would do this check in our code.

if (String.IsNullOrEmpty(mystring) || mystring.Trim().Length == 0){//code here}

We can be more efficient by writing like this:

if (String.IsNullOrWhiteSpace(mystring)){// code here}

Ternary Operator

This is an operator we use when we need to check for conditions and it returns one of the values depending on the
Boolean expression.

For example if there is a check in your code like the following:

if (mystring == null){mystring="this is new text";}else{Mystring = "exisiting string";} 

You can write the above code using the ? Operator like below:

     mystring = (mystring== null) ? "this is new text" :"existing string";


Null Coalescing Operator

The ?? Operator or the Null Coalescing Operator is used to return the left hand operand if it is not null otherwise it
returns the right hand operand.

For example there is a check in your code like the following:

string mystring = null; if (mystring == null){mystring = String.Empty;} 

We can write the above code like the following using the ?? Operator: 

 string mystring = null ?? String.Empty;


Stopwatch Class

There are a lot of instances with us that we need to time a particular portion of our code or any external process
running from our code for which the control comes back to us. We usually use the DateTime object and assign to the
start variable, than run our process and then assign it to the end variable when the process is over and than just find
the difference between them and display on the screen. Here we can see that using Stopwatch class is also very
helpful in these tasks:


Stopwatch timer = Stopwatch.StartNew();

     // time intense code here


     Console.WriteLine("Method took {0} ms", timer.ElapsedMilliseconds);


You can reset the Stopwatch with just Reset() method.

TimeSpan Structure

Sometimes we need to use seconds or milliseconds in our code for some purpose, for example:


Thread.Sleep(4000); // this would suspend the current process by 4 seconds


But if the number is large than it becomes hard to read as we don't know if we need to convert this to seconds or
minutes. Alternative to this is to use the TimeSpan structure which is precise in its parameters as either hours,
minutes, seconds, milliseconds or days are being passed in the parameter. Following is the revised code for the above

Thread.Sleep(new TimeSpan(0,0,4)); // this would also suspend the current process by 4 seconds, but much readable now.


Hope you enjoyed this article and found these little treats useful and that you can make use in your code to make it
more readable and code fast.