7 Common Mistakes Made By C# Programmers

Introduction

Making mistakes is inevitable in programming. Even a small mistake could prove to be very costly. The wise thing is to learn from your mistakes and try not to repeat them. In this article I will be highlighting the mistakes which I consider to be the 7 most common mistakes made by C# developers.

Formatting a string

There lies the strong possibility of making costly mistakes while working with string types in C# programming. String is always an immutable type in the .NET Framework. When a string is modified it always creates a new copy and never changes the original. Most developers always format the string as shown in the sample below:

  string updateQueryText = "UPDATE EmployeeTable SET Name='" + name + "' WHERE EmpId=" + id;

The above code is really messy and also as the string is immutable it creates 3 unnecessary garbage string copies in the memory as a result of multiple concatenations.

The better approach is to use string.Format as it internally uses StringBuilder which is mutable. It also paves the way for a clean code.

  string updateQueryText = string.Format("UPDATE EmployeeTable SET Name='{0}' WHERE EmpId={1}", name, id);

Nested Exception Handling

Developers who intend to write nested methods end up doing exception handling for each methods as shown in the below code:

  public class NestedExceptionHandling
  {
      public void MainMethod()
      {
          try
          {
              //some implementation
              ChildMethod1();
          }
          catch (Exception exception)
          {
              //Handle exception
          }
      }

      private void ChildMethod1()
      {
          try
          {
              //some implementation
              ChildMethod2();
          }
          catch (Exception exception)
          {
              //Handle exception
  	     throw;

          }
      }

      private void ChildMethod2()
      {
          try
          {
              //some implementation
          }
          catch (Exception exception)
          {
              //Handle exception
              throw;
          }
      }
  }

So what would happen with the above code if the same exception were handled multiple times and more over catching exceptions, throwing it will definitely add a performance overhead.

I try to avoid this by putting the exception handling in a single place that is in the MainMethod as shown below:

  public class NestedExceptionHandling
  {
      public void MainMethod()
      {
          try
          {
              //some implementation
              ChildMethod1();
          }
          catch(Exception exception)
          {
              //Handle exception
          }
      }

      private void ChildMethod1()
      {
          //some implementation
          ChildMethod2();
      }

      private void ChildMethod2()
      {
          //some implementation
      }
  }

Using Foreach on Huge Collections

Most developers prefer to use a foreach loop than for loop because foreach is easier to use. This will however prove to be costly when working with collections with a large amount of data. Consider the below sample in which I am looping through the same datatable using for and foreach. Also check the time taken by each loop on Fig 1.0.

  static void Main(string[] args)
  {
      DataTable dt = PopulateData();
      Stopwatch watch = new Stopwatch();

      //For loop
      watch.Start();
      for (int count = 0; count < dt.Rows.Count; count++)
      {
          dt.Rows[count]["Name"] = "Modified in For";
      }
      watch.Stop();
      Console.WriteLine("Time taken in For loop: {0}", watch.Elapsed.TotalSeconds);

      //Foreach loop
      watch.Start();
      foreach (DataRow row in dt.Rows)
      {
          row["Name"] = "Modified in ForEach";
      }
      watch.Stop();
      Console.WriteLine("Time taken in For Each loop: {0}", watch.Elapsed.TotalSeconds);

      Console.ReadKey();
  }

time taken by each loop
Fig 1.0

As you can see the foreach loop is slow, it takes almost double the amount of time as that of the for loop. This is because in the foreach loop dt.Rows will access all the rows in the datatable.

For bigger collections always use for loop in case if looping is required.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read