Tips for Writing Clean C# Code

Any developer can write code with enough training and practice. There are references aplenty if a programmer cannot remember how to call a function or forgets a functions parameters. Becoming a programmer is less about remembering exact syntax and more about understanding the core principles and structures of a programming language. Of course, knowing the syntax for the fundamentals is essential – don’t get me wrong. To become a good programmer (or a great programmer), a developer needs to take things a step further and learn how to write clean code.

What is clean code? How does a developer write clean code and avoid sloppy, “spaghetti” code? We will discuss some basic principles of writing clean, readable C# code in this programming tutorial.

Read: C# Data Types Explained

What is Clean Code?

To begin, there is no real definition of clean code; if asked, every programmer will likely have their own definition and rules. Some of those thoughts will, of course, overlap, and from that overlap, we can loosely define what clean code is.

Despite what school teachers will tell you, sometimes it is okay to assume, as we are going to do here. With that said, here it is: it is safe to assume that clean code, for most developers, means code that meets the following criteria:

  • Code is easily readable
  • Code is clearly defined and documented
  • Code is scalable per the needs of the project
  • Code is efficient and all excess code (i.e.; commented out code that will no longer be used under any circumstance) has been removed
  • Code that follows the specific best practices for that language’s best practices. In our case, that is C#.

All of that can be summarized in one simple statement: clean code is code that is easy to read, understand, maintain, and change. Period.

How to Write Clean C# Code

Here are some basic steps C# developers can take to ensure their code is clean and following best coding practices.

Use a C# Integrated Development Environment (IDE) or Code Editor

Before a developer even begins to code, they need to make sure they have an environment that will help them write the most efficient and error-free code. Whether a programmer chooses to write their applications in a code editor or integrated development environment (IDE) will depend on the developer’s personal preference or the developer tools made available to them by their development team. Whatever the case, the only way to really write clean C# code is to take advantage of a C# IDE or code editor.

The best coding environments will have features such as syntax highlighting, auto-complete, and code suggestions. All of these features help a coder better organize their code and make sure the syntax is neat and written properly. For C#, popular IDE’s and developer tools include Visual Studio, Visual Studio Code, and several of the popular Jet Brains coding tools, such as Rider.

Read: Working with Strings in C#

C# Naming Conventions for Functions, Variables, and More

Each programming language has its own set of rules for the proper naming of variables, functions, and the like. C# is no different in this respect. When naming objects in your programs, such as variables, always be certain to follow naming convention rules, such as the case objects should be named in (for example: camelCase, PascalCase, and _underscore).

In C#, naming conventions include the following:

  • Parameters: lowerCamelCase
  • Variable: lowerCamelCase
  • Class: PascalCase
  • Method Name: PascalCase
  • Method Argument: camelCase
  • Property: PascalCase
  • Public Field: UpperCamelCase
  • Private Field: _lowerCamelCase
  • Constants: PascalCase
  • Constructor Name: PascalCase
  • Namespace Name: PascalCase

Also, when naming variables and functions, be certain to name them something that makes sense and describes their intent. For instance, let’s say you want to create an int variable that will represent a date of birth – you should avoid giving it a generic name such as:

int date;

Instead, you should give it a name that you – or a future developer – can immediately recognize the intent of the variable:

int dateOfBirth;

C# Code Formatting

Every development team should have a style guide and that style guide should include how code will be formatted. In particular, you will want to decide whether your team is using spaces or tabs to indent code. There is a lot of debate in the developer community over which is, technically, better to use (meaning which is more efficient) – that is not an argument we need to have today! The point is, however, that you do need to make a decision if you want your code to be clean. Make a choice between the two options and stick with it; do not mix your spaces and tabs!

A side note: this is another reason why a code editor or C# IDE can come in handy – most will automatically handle this aspect of code formatting for you, leaving your brain to focus on other matters, such as what name your pets gave you.

Commenting C# Code

If writing clean C# code means writing code that is readable and understandable, then making sure you properly comment your code only makes sense. This should be a part of your best coding practices anyway – for your own sake if not every one else’s that will ever view or work with your applications.

Commenting, believe it or not, can be done poorly. It is not enough to just randomly slap some comments here and there in your program. Developers need to write good, quality comments just as much as they need to write clean code. For example, avoid leaving comments that are unnecessary or literally say exactly the same thing that your code does. For example, look at this line of code and its preceding comment:

class Program
{

static void Main(string[] args)
{
///  Print "My name is James Payne and I am the World's Greatest Writer!"

	Console.WriteLine("My name is James Payne and I am the World's Greatest Writer!");
}

In our above code, we created a program that prints a very true statement to the user’s screen. At a glance, any developer could tell you what that block of code does, so the comment we added offers zero value or help. In fact, all it serves to do is clutter our code by adding more distractions.

In cases where the code is self-explanatory, feel free to not leave comments. If you find yourself writing lazy comments that explain your reasoning behind writing the code in the first place – versus explaining what the code does – then consider changing the code itself. You should never have to convince anyway why you wrote code; having to do so could indicate that your code is not optimal.

Read: Commenting Best Practices for C#.

Concatenation in C#

Here is a fun C# no-no: string concatenation in loops. Avoid the use of the concatenator operator – or ‘+‘ – in loops. This can lead to some unwanted and unplanned results, leading to errors in your program or unexpected outputs. Instead of writing:

string test = "";

for (int i = 0; i < arrayOfNames.Length; ++i)
{
	test = test + arrayOfNames[i];
}

You should use the StringBuilder concatenation method instead. For example, the above code would instead read:

StringBuilder namesApp = new StringBuilder();
for (int i = 0; i < arrayOfNames.Length; ++i)
{
	namesApp.Append(arrayOfNames[i]);
}

string test = namesApp.ToString();

Pay Attention to Change Logs

As technology changes, programming languages must change as well. Indeed, programming languages, like the human languages, are ever-evolving and (mostly) improving. Because of that, a good developer will take note of their given programming languages changelogs when new version arise. One aspect of changelogs to take note of is deprecations. A deprecation in a changelog refers to a change to some element of the language whose use is now being discouraged, but not prohibited. For instance, Thread.Resume and Thread.Suspend have been deprecated in C# because they can lead to deadlocks. However, they still, technically, exist within the language and a developer could use them.

The majority of the time once something is deprecated in a version of a language, it will be slated to be removed entirely from a major update of the language later on down the line. As such, when a new developer looks at your code, they may not even recognize the deprecated part of code you input, let alone the fact that the code will cause errors once it is updated (if it does not already – that element was deprecated for a reason!).

Keep up with changelogs and be forward-thinking to keep your code clean even after you have written it.

Read: Working with Math Operators in C#

Handling Exceptions

There are some definite things to look out for when handling exceptions or when exceptions are thrown. These include the following scenarios:

  • Do not throw exceptions in a finally block, as this can mask previous exceptions in the try-catch block.
  • Do not use non-public exceptions; all exceptions should be public.
  • Avoid throwing general exceptions such as Exception or SystemException.
  • Explicitly throwing an exception can interfere with the debugging process; call throw instead.
  • Avoid throwing exceptions from the following: GetHashCode, ToString, static constructors, Object.Equals, implicit cast operators, and comparison operators (==, !=, <, <=, >, >=).

Do Not Use the goto Statement in C#

As a young developer, coding in QBasic, I learned the errors of relying on the goto statement, as it invariably led to the dreaded “infinite loop” in my programs. I was eight – I have never forgotten the lesson, all these years later.

There are some cases where a goto statement is useful and, perhaps, even recommended, but when you can, avoid its use, as it can make the program flow difficult to understand. When possible, use other control structures such as break, continue, for, or even an if.

Refactoring C# Code

Finally, clean code is code that has any extraneous code removed from it. That is why refactoring your code is one of the best ways to make sure your codebase is clean and efficient. There are plenty of C# code refactoring tools on the market, including JetBrains’ ReSharper. You can also check out our article on Code Refactoring Tips for C# for some additional ideas.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read