5 Bad Practices to Avoid in C#

In this post, I want to give 5 little examples of bad practices in C# and what can be done instead to improve your code a little bit. If you are an intermediate C# developer, you should know these already, and if not you will learn them today.

Use Ternary Operator Instead of If Else

In most cases, it’s cleaner to use a Ternary Operator instead of an If Else condition because it will take less space and will make your code more readable.

if (age >= 18)
{
    return "You are an adult";
}
else
{
    return "You are not an adult";
}

We can fit these 8 lines in one line like this:

return age >= 18 ? "You are an adult" : "You are not an adult";

Use Enum Instead of Hard-Coded Numbers

Whenever you can use an enum instead of a random number in your code, it will increase the readability of your code and reduce the possibility of making mistakes.

Don’t do this:

if(month == 2)
{
    days = 28;
}

Instead, do this:

enum Months
{
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,       
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12
}

if((Months)month == Months.February)
{
    days = 28;
}

 Use Null Coalescing Operator

Null Coalescing Operator will let you assign a default value when a variable is null, and that can be done in a single line instead of using a multi-line if else condition.

Don’t do this:

public Book GetTheBestBook(Book book)
{
    if (book != null)
    {
        return book;
    }
    else
    {
        return new Book() { Name = "C# in Depth" };
    }
}

Instead, do this:

public Book GetTheBestBook(Book book)
{
    return book ?? new Book () { Name = "C# in Depth" };
}

Use String Interpolation

String interpolation using $ is a .Net 6 feature that makes your code look better.

public string GetTheBestBookName(Book book)
{
    return "The Best book's Name is " + book.Name + " and the author name is " + book.Author;
}

This looks better:

public string GetTheBestBookName(Book book)
{
    return $"The Best book's Name is {book.Name}. and the author name is {book.Author}";
}

Do Proper Exception Handling

Shouldn’t do throw ex; when you catch an exception because that will lose the Stack Trace when it goes to the higher layers. You should either log the exception or do throw; and log in at a higher layer.

Don’t do this:

try
{
  
}
catch(Eexception ex)
{
  throw ex;
}

Instead, do this:

catch(Exception ex)
{
  Logger.GetException(ex.Message);
}

Or this:

catch(Exception ex)
{
  throw;
}