Common Mistakes in C# Programming

Heitor Helmer Herzog
3 min readApr 21, 2018

--

  1. Using string concatenation incorrectly
    In older languages, it was common just to use the plus sign to concatenate strings. The problem with this is that it’s an inefficient way to concatenate strings, so Microsoft introduced StringBuilder to help with memory and performance issues.
    Use StringBuilder whenever you want to concatenate strings or manipulate them throughout your code. You don’t always need to use them for simple, basic strings, but it’s useful when you need to take a list of values such as those from a file and put them together to create one input that you then output to the user, or store to your database.
  2. Not disposing of objects
    Memory leaks (also called resource leaks) are a real problem for any application. C# provides you with a convenient way to call the Dispose method after you’re finished with an object, so you don’t even need to remember to use it. The “using” statement will dispose of an object and avoid troublesome memory leaks.

Inefficient
file.Read(buffer, 0, 100);

In the code above, if you don’t dispose of the file object, you create a memory leak in the application. You can avoid this situation with the using statement.

Efficient
using (FileStream file = File.OpenRead(“numbers.txt”)) {
file.Read(buffer, 0, 100);
}

Now the application reads a file and disposes of the object when it’s finished.

3. Iterating through values instead of using linq
In almost any application, you’ll eventually need to enumerate values and store them in a List or a Collection. You could end up having to iterate through thousands of records. Consider pulling a list of customers, for example. If you have 100,000 customers, iterating through each of them just to find a specific data set isn’t efficient. Instead of using a foreach or for loop, use LINQ (Language-Integrated Query), which is an integrated .NET feature that’s designed to make it easier to query objects such as collections and lists.

Here’s an example:

Inefficient Way

foreach (Customer customer in CustomerList) {
if (customer.State == "FL") {
tax += customer.Balance;
}
}

Efficient Way

var customers = (from customer in CustomerList
where customer.State == "FL"
select customer.Balance).Sum();

One line of LINQ code is all you have to execute, and it returns 1000 customers, instead of grabbing 100,000 customers. Working with 1,000 customers at a time is much more efficient than iterating through each of the 100,000.

4 . Not using yield return
When enumerating over objects for another caller you should use yield return instead of creating a return collection. Some benefits of this pattern are that:
* You don’t have to keep the whole collection in memory (it might be pretty big)
* Yield return immediately returns control to the caller after each iteration
* You only process results that actually are used (why iterate the whole collection if the caller just wants the first item?)

5 .Parsing ambiguous dates

Be sure to specify a format provider when you parse ambiguous dates. For example, it is not clear what part of the date string “03/04/05” that are the month, day, and year and it can lead to serious errors for a user. Use DateTime.ParseExact / DateTimeOffset.ParseExact to provide the specific format:

var date = DateTime.ParseExact("01/12/2000", "MM/dd/yyyy", null)

6 . Rethrowing Exceptions with an exception instance

If you want to catch and rethrow an exception, be sure to use the simple throw; syntax. If you use throw ex; it will not preserve the exception call stack.

DO:

catch(SomeException ex)
{
logger.log(ex);
throw;
}

DON’T:

catch(SomeException ex)
{
logger.log(ex);
throw ex;
}

--

--

Heitor Helmer Herzog
Heitor Helmer Herzog

Written by Heitor Helmer Herzog

Software developer, In love with games and the industry. Let’s code! About me: www.linkedin.com/in/heitorhherzog

No responses yet