5 (Important) Tips to Writing Clean C# Code
Tags: csharp, dotnet, programming, beginners
Published: 2022-02-09 11:33:00

One of the most important skills of a C# programmer is **writing clean, efficient code** that performs well and can be easily maintained by others who will inherit your code after you've moved on to other projects. This can seem like an impossible task, as there are many factors to consider when writing C# code, including variables, methods, classes, and types, just to name a few. But with these five tips, **you can learn how to write clean C# code** that's easy to read and understand by others on your team.

---

## Use variable names that are easy to remember

This malpractice is one of the most common. Many times we  -_ the .NET developers_ -  want to complicate a lot when in most of the occasions it is not necessary.

When declaring a variable, **we should use a name that makes sense,** that is easy to remember and that is easy to pronounce.

**Bad way:**

```csharp
var yyyymmdstr = DateTime.Now.ToString("YYYY/MM/DD");
```

**Good way:**

```csharp
var currentDate = DateTime.Now.ToString("YYYY/MM/DD");
```

This does not seem to be important, but once the project develops and becomes larger, **the number of variables will be very large.** And we all know that when we open a project after a long time without opening it, **many times we don't know what some part of the code does.**

---

## Variable name consistent

Many times it has happened to us that we declare variables but we declare each one with a different structure or  - _lexically speaking_ - with a different vocabulary. Let me explain:

We should always look for the greatest simplicity. We should always use the same word and not vary it  - _I mean synonyms_. Let's see a practical example.

**Bad way:**

```csharp
getUserInfo();
getClientData();
getCustomerRecord();
```

**Good way:**

```csharp
getUser();
```

In that example, we can clearly see that in the bad way we are using different synonyms for the same word. This may cause confusion in the future, both for the current developer and for the (_possible_) future developer who will have to understand the code.

---

## Use searchable names

I am sure that more than once you forget where _something_ is and you start looking for that _something_ but you can't find it because you don't remember what name you gave to the variable or directly, you don't remember if you named that constant. For your better understanding:

**Bad way:**

```csharp
// In the future we will not remember what 86400000 means.
clearBacklog(backlog, 86400000);
```

**Good way:**

```csharp
// Declare constants with a searchable name
var MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;

clearBacklog(backlog, MILLISECONDS_PER_DAY);
```

This small practice, although it may not seem like it at the time, **will save us many hours of searching and quite a few headaches** (both for us, the current developers, and for potential future developers). **Remember:** The easier to read code, the better.

---

## Don't repeat yourself

This error is very common because we unconsciously repeat names or words. This bad practice in the long run makes you have a very dirty code since there will be many things that will be repeated. Let's get down to practice:

**Bad way:**

```csharp
Bike MountainBike = new(){
   bikeBrand = "Trek",
   bikeModel = "MX Mountain",
   bikeColor = "Green"
};

void paintBike(Bike mountainBike, string color){
     mountainBike.bikeColor = color;
}
```

**Good way:**

```csharp
Bike MountainBike = new(){
   brand = "Trek",
   model = "MX Mountain",
   color = "Green"
};

void paintBike(Bike mountainBike, string color){
     mountainBike.color = color;
}
```

In this way we can see that by spending less time thinking and writing, **we get a much cleaner and easier to read code** (which we will thank ourselves in the future for having done).

---

## Uses highly descriptive variable names

Another bad practice is to send functions directly as an argument of another function. This only causes a lot of confusion and makes our heads hotter than an old _AMD FX_ series processor.

**Bad way:**

```csharp
const address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeRegex = new Regex(@"/ ^[^,\\] +[,\\\s] + (.+?)\s * (\d{ 5 })?$/").Matches(address);
saveCityZipCode(
  cityZipCodeRegex[0].Value,
  cityZipCodeRegex[1].Value
);
```

**Good way:**

```csharp
var address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeRegex = new Regex(@"/ ^[^,\\] +[,\\\s] + (.+?)\s * (\d{ 5 })?$/").Matches(address);
var city = cityZipCodeRegex[0].Value;
var zipCode = cityZipCodeRegex[1].Value;
saveCityZipCode(city, zipCode);
```

The solution, as we can see, is to **add the resulting values in variables and then send those variables to the function.** This will allow us to understand in a simpler way the information that you are sending to it and besides, we will save a _Noctua_ heatsink for our head.

---

I know these little tips are pretty simple (although I'm sure not all of you will follow them😏). The number of ways to write cleaner code in C# **is more infinite than the universe.** So, I'm going to make a list of **Cleaner C# Code** posts, in which, we will touch on more advanced tips and some other tricks to improve the quality of our code.

If you are interested, don't forget to follow us so you don't miss any news!