Do you know these C# conventions?

Is there a “good” way to write C#?

This article is also available on Medium.

When you program a project, the first step is always to have something that works. But then, when you’ve managed to implement your feature, it’s often a good thing to try and clean up your code…

… and, for example, you can make sure that it obeys the usual C# conventions to make it easier to understand by other collaborators, or contributors on an open source project!

So, today, let’s have a look at those and help make sure your next piece of software is all shiny and fancy 🙂

Foreword

In this article, we’ll mainly discuss conventions from the Microsoft C# docs. But keep in mind that your team and project conventions, if they are already established, should always supersede this global reference. It is better that you and your colleagues understand each other and create consistent software, than that you alone follow some strict guidelines from an external source!

And, of course, the conventions I show here are just one possibility — feel free to react in the comments if you have some advice of your own!

How should you name your classes and variables?

Ok — first of all, let’s see some naming conventions 🙂

When you decide on the name of a variable, or a class, or an interface, or any other object in your code, you can basically choose two things:

  • how long it is
  • how the “words” in it are separated

The length of a variable is important because picking a super-short name can sometimes be risky and make it hard to understand your code. There are obviously some special cases, like x, y, z coordinates, or the min and max… but more often that not, replacing things like candidatesList with a simple l leads to a pretty unreadable programs. On the other hand, if all your variable names are three lines long, they will just cram everything and annoy your teammates just as much.

Basically, you should always try to your best to balance length and clarity — and in my opinion, when in doubt, favour the later slightly 😉

Then, if your name is a group of multiple words, such as candidatesList earlier, you have to help people properly distinguish between each word. To do this, there are several types of casing, among which most notably:

  • PascalCase 
  • camelCase 
  • snake_case 
  • kebab-case 

In C#, the two you use the most frequently are PascalCase and camelCase: basically, the classes, structs and interfaces use PascalCase and all the rest uses camelCase. However, there are some special prefixes too:

  • interfaces should start with I, for example: IMyInterface 
  • private fields can start with an underscore _, for example: _myInt 

The Microsoft docs have a bit more prefix rules but they’re not necessary used by everyone, so we won’t go into more details here.

How should you write your comments?

To further guide your readers through you code, another useful tool are the comments. Although some programmers consider that good code should be self-sufficient and self-explanatory, there are some cases where you may want to explain some decision or a global algorithmic process. And that’s when you use comments.

To write comments, you can either put two slashes at the start of the line, or a slash and an asterisk to create a block of comments:

Comments are typically something that, in my own experience, can be quite different from one team to another. There is no golden standard here and, since this part is totally independent from the programming language you use, it can even be in whatever language your team prefers!

Usually, however, it is recommended to avoid putting comments at the end of a line of code — rather, you should put them before on a separate line. Also, since comments are more natural language, some guidelines advise you to put an upper letter at the beginning of your comment and a dot at the end to write a “real sentence” 😉

How should you handle your LINQ queries?

Following our previous remarks on variable naming and casing, let’s also quickly discuss LINQ queries. You probably already know this really nice built-in C# tool for managing containers, mapping, filtering and reducing (but if you want some refreshers, feel free to read through this other article I wrote about it 😉 ).

It’s a very good way to simplify your code and process your data with a few keywords, for example:

With just these three lines, you’ve extracted the three entries in your leaderboard table with the highest score, and it’s fairly easy to read, too!

But to keep it that explicit and somewhat efficient, you have to insure that:

  • you properly name the different variables, even the intermediary ones
  • you use the new keyword to rename fields that could later be confusing, like a global “id” or “name”:
  • you do any filtering (with the where keyword) first so that the rest of the process is done on a reduced subset of data

Aligning everything under the from clause like in the previous examples is also a good habit to have when using this tool 🙂

Finally, note that you can even use the new keyword to rename some fields from the incoming data and better match your current code conventions:

A few additional suggestions

  • If you want to display and concatenate some strings, the easiest way is to use string interpolation, like this:

If you want to learn more about this technique, check out this other article I did on this topic 🙂

  • The var keyword is pretty powerful but it can also hinder readibility a bit. In particular, when possible, you should not use it in foreach loop since the type of the iterator is not always immediately obvious.
  • If you use this var keyword, also make sure that you don’t rely on the name of the variable to specify its type. For example, the following snippet is quite misleading cause the variable age should be an integer but actually contains a string!
  • When you declare an array with an explicit type and initialise it directly, you can actually skip the new X[] part:

Conclusion

And there you are, those were just a few common C# conventions to make your next projects all fancy! If you plan on sharing it with other devs or if you collaborate on this with your work teammates, following guidelines is a crucial way to insure the codebase is readable and consistent…

So don’t forget to go one step further after you’ve implemented your feature, and take some time to clean up your code 😉

Anyway, I hope you liked the tutorial — and as usual, thanks a lot for reading, and don’t hesitate to share your own C# conventions and tricks in the comments!

Leave a Reply

Your email address will not be published.