DEV Community

Cover image for 🚨7 MISTAKES made by C# programmers (+ 🎁GIFT)
Dotnetsafer
Dotnetsafer

Posted on • Updated on

🚨7 MISTAKES made by C# programmers (+ 🎁GIFT)

Developers are ALWAYS going to make mistakes, no one is perfect. Many of them, especially C# developers, learn and improve by trial and error. I like to call it "transitioning" from junior developer to senior developer.

Although this trial-and-error "strategy" works, if a developer doesn't catch mistakes, they can cause many efficiency and quality problems in the developed software.

In this article I have gathered the most common and not so common mistakes that many C# developers make.


❌ 1. Usage of String Concatenation

The way String Concatenation Functions works is very easy to understand 👇

Every time something is added to the string, a new address is allocated in memory automatically. The previous string is copied to the new part with the changed location (this is not efficient at all)

Let's see an example taken from AspireSys 👇

List dotnetsaferTools = new List(){"Shield","Secrets","Linker"};
string tools = string.Empty;
foreach (var tool in dotnetsaferTools)
{   
  tools += tool; // Creates a copy of the string in memory
}
Enter fullscreen mode Exit fullscreen mode

✅ Solution

The way to solve this is simple, you have to use StringBuilder object instead of string aggregation which will keep the same position in memory without any copy task.

This makes the string concatenation process much simpler and more efficient, so we can seamlessly append all the operations we want.

This is how it would look like 👇

StringBuilder toolsBuilder = new StringBuilder();
foreach (var tool in dotnetsaferTools)
{
  toolsBuilder.Append(tool);
}
Enter fullscreen mode Exit fullscreen mode

❌ 2. Iterating with Values instead of with LINQ

This error happens when you try to iterate lists of records with a loop, not optimal at all.

foreach (Customer customer in CustomerList) {
  if (customer.State == "ES") {
    tax += customer.Balance;
  }
}
Enter fullscreen mode Exit fullscreen mode

✅ Solution

Instead of doing this, we should simply use LINQ which will allow us to query objects easily.

tax = CustomerList.Where(customer => customer.State.Equals("ES")).Sum(c=>c.Balance);
Enter fullscreen mode Exit fullscreen mode

📚 This is more efficient than a foreach loop.


❌ 3. Not using Yield Return

This is for when you need to create an object enumeration for some other caller. Using this function will greatly improve performance.

✅ Solution

To avoid making this mistake, you should simply not try to create a return collection. The big advantage of using yield return is that the entire collection will not have to be stored in memory.
This will allow you to have control after each iteration and you will only process the results that you need and that are necessary.


❌ 4. Deferred Execution in LINQ

The main one of LINQ is to facilitate querying data in case we use foreach loops (an example is nested if blocks). To get a list of clients, I recommend using LINQ-to-SQL.

public IEnumerable GetCustomers()
{
  using(var context = new DBContext())
  {
    return from c in context.Customers
      where c.Balance > 2000
      select c;
  }
}
Enter fullscreen mode Exit fullscreen mode

It seems that everything is fine, isn't it? Only until we try to enumerate the collection (it will return an exception).

What happens is that LINQ will not perform any query until we try to enumerate results.

✅ Solution

 The solution is simple, just convert all LINQ queries to a ToArray(). By doing this, LINQ should evaluate the queries before anything else.


❌ 5. Accessing Virtual Members within a Constructor

Although this error is not one of the first, it is one of the most common, although it may not seem so. 

When an overridden method is called directly from the constructor of a base class, this error will appear because it comes from executing code before its time.

public class Parent
{
  public Parent()
  {
    Console.WriteLine("Parent Ctor");
    Method();
  }

  public virtual void Method()
  {
    Console.WriteLine("Parent method");
  }
}

public class Child : Parent
{
  public Child()
  {
    Console.WriteLine("Child Ctor");
  }

  public override void Method()
  {
    Console.WriteLine("Child method");
  }
}
Enter fullscreen mode Exit fullscreen mode

✅ Solution

Although it may seem very complex, it is actually very easy. We simply have to mark that class as sealed.

What does this do? 🤔

By doing this, we make sure that when we call the virtual method, we will not receive any warning.


❌ 6. Not knowing the importance of USING for Object Disposal

As partech.nl says, many C# developers are unfamiliar with the concept that the using keyword is not only used as a directive for adding namespaces, but is also very beneficial for object removal.

✅ Solution

If you are really sure that an object should be deleted when performing certain actions, simply use the using statement to make sure that the object has been deleted correctly.

Let's see an example 👇

using(DisposableClass DisposableObject = new DisposableClass())
{
  DisposableObject.DoTheJob();
}
// Does the same as:
DisposableClass DisposableObject = new DisposableClass();
try
{
  DisposableObject.DoTheJob();
}
finally
{
  DisposableObject.Dispose();
}
Enter fullscreen mode Exit fullscreen mode

❌ 7. Using Weak Cryptographic Algorithms

Here we agree with Stackify, this error is simply based on the fact that many developers use obsolete or vulnerable encryption algorithms (which is very easy to avoid).

In this case we have for example SHA1 or RIPEMD160, which do not offer a current and very good level of security.

using System.Security.Cryptography;   
...   
var hashAlg = SHA1.Create();
Enter fullscreen mode Exit fullscreen mode

✅ Solution

The solution to this is to use stronger encryption algorithms, for example:

  • SHA256 instead of SHA1
  • SHA512 instead of RIPEMD160
  • AES instead of TripleDES

🎁 Do you want a gift?

If you are reading this, it means that you belong to the 1% of people who read the articles UNTIL THE END and for that you GET a GIFT🎁!!!! But first you must give a unicorn 🦄 (So I will know who are the faithful ones who read the whole articles 💜).

Just for entering this article and making it this far, I’m GIVING you a GIFT of a GUIDE to keeping your .NET applications secure 🎁.

Dotnetsafer Security Book

The ONLY thing you have to do is enter your email to receive it for FREE 🤑.

🚨 This won’t be around forever.

To maintain exclusivity, I’ll be editing the article soon and there will no longer be a gift. So HURRY UP and get your guide to becoming a .NET security expert! 👇👇👇

Download FREE guide 🎁

Discussion (0)