Skip to content

Instantly share code, notes, and snippets.

@SimonCropp
Last active January 18, 2020 18:30
Show Gist options
  • Save SimonCropp/0d0e711dc21118981e7781259d5e98e3 to your computer and use it in GitHub Desktop.
Save SimonCropp/0d0e711dc21118981e7781259d5e98e3 to your computer and use it in GitHub Desktop.
Consider not using namespaces

Over the years C# has been criticised for being too verbose. This is especially common when compared to languages like Scala, FSharp, Erlang, Ruby and Javascript. There is no arguing that the syntactic constructs in these languages allow for a much terser coding style. However C# can be more succinct than people realize.

So with the idea that "less code is better code", what can be changed about how we code C#?

There are a few solutions, for now, I'm going to focus on:

Consider NOT using namespaces

This might sound crazy but bear with me.

So what are namespaces for? Well, from MSDN [http://msdn.microsoft.com/en-us/library/z2kcy19k%28v=vs.80%29.aspx][1] :

The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types.

The important part of this statement is “create globally unique types”. It essentially ensures that when other people reference our assembly they will not have naming conflicts. There are many cases where this is essential. For example, any type of framework or library assembly that is referenced by many third parties must ensure no type naming conflicts occur.

However, did any of us stop to think if we need to prevent naming conflicts on all our assemblies? I would consider myself lucky if all my code was used globally, but this is not the reality. The vast majority of code is used within the bounds of a single company and often only in a single application. So do we really need the MSDN recommended (globally unique) approach to namespaces?

I can think of several specific cases where this applies. The reason being that nothing outside the solution references them.

  • Test assemblies
  • Front end code (Website, Silverlight and Windows forms), and
  • Any type of console application.

So, in these cases (and many others) using namespaces, and the obligatory indentation, is just noise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment