Since C# 10 (.NET 6.0) arrived my code looks much cleaner. Less code is less waste, which is good for the environment!
C# 10 achieved this with top-level statements, global using directives and file-scoped namespace declaration.
It’s even spin off a new fresh way of creating Web API’s: Minimal API.
But what can you do to make C# greener?
β remove the public access modifier on classes, structs and records. By default, when creating a class, it’s public. This is often not what you want, so remove it and it will default back to internal.
β remove the private access modifier on members. Private is already the default for members, so remove it. At first it will look strange but give it a couple of days.
π‘ Tip: Change the code inspection in ReSharper or Rider from explicit to implicit to help you!
β use records for DTO’s. Your code becomes cleaner, by writing less plumbing code. You also get better logging for free, because the ToString() shows the value of each member.
β use switch expressions and pattern matching, when possible, to simplify your code. Combine these two for the ultimate cleanup.
What are your tips to make C# greener?