Implicit Usings in .NET 6
".NET 6 introduces implicit namespace support for C# projects. To reduce the amount of
using directives boilerplate in .NET C# project templates, namespaces are implicitly included by utilizing the
global using feature introduced in C# 10."
NOTE: Did you know that Visual Basic has had this very feature forever?
Remember that C# as a language is itself versioned and in .NET 6 we'll have support for C# 10 features like global usings, which are super cool.
Since we don't want to break existing stuff, there's some things to consider. First, for new projects this is on by default but for existing projects this will be off by default. This offers the best of both worlds.
When you create a new .NET 6 project it will enable this new property:
Read more about this breaking change here. This build property builds upon (utilizes) the C# global using feature feature which means any .cs in your project can have a line like:
global using global::SomeNamespace;
The SDK uses a target to autogenerate a .cs file called ImplicitNamespaceImports.cs that will be in your obj folder, but you can - if you desire - have full control and add or remove namespaces to taste.
This gives advanced users who understand target file a huge amount control while still allowing newbies to reap the benefits. Other way to think about it is - if you care, you can control it all. If you don't, it'll just make things easier and cleaner.
Let's look at some code to point out that it's pretty cool. Oleg gives a great example doing some basic threading where there's three lines of code (cool) and three more lines of usings to bring in the namespace support for the actual work (less cool).
List<int> _ = new ();
With implicating usings (implicitly bringing in default namespaces) .NET apps with C# 10 can do more out of the box. It's faster to get started because the 90% of the stuff you do all the time is already available and ready to be used!
Maybe this example is too simple? What If you were using a simple Web Worker app? Check out Wade's example.
This is a lot of boilerplate if you just want a web app. If I'm using the Microsoft.Net.Sdk.Worker SDK in my project file, or just Microsoft.NET.Sdk.Web, I don't have think about or include any of these - they are there implicitly!
You may initially love implicit usings, as I do, or you may find it to be too "magical." I would remind you that most innovations feel magical, especially if they aren't in your face. The Garbage Collector is taken for granted by the majority of .NET developers, while I found it magical when I had spent the previous 10 years managing my own memory down to the byte.
Hope you enjoy this new feature as we get closer to .NET 6's release.
Sponsor: The No. 1 reason developers choose Couchbase? You can use your existing SQL++ skills to easily query and access JSON. That’s more power and flexibility with less training. Learn more.