Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I able to use C# lists without writing "using System.Collections.Generic;" at the beginning of my file?

Take a look at this simple C# program:

using System;

namespace testProgram
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            list.Add("List element.");
            Console.WriteLine(list[0]);
        }
    }
}

Output:

List element.

You can see that it uses a list. I always saw on the Internet that in order to use a list, I need to add "using System.Collections.Generic;" at the beginning of my file. However, the program can run without this line, why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Look at your project file. I strongly suspect it will include this:

<ImplicitUsings>enable</ImplicitUsings>

The ImplicitUsings feature is described here:

The ImplicitUsings property can be used to enable and disable implicit global using directives in C# projects that target .NET 6 or a later version and C# 10 or a later version. When the feature is enabled, the .NET SDK adds global using directives for a set of default namespaces based on the type of project SDK. Set this property to true or enable to enable implicit global using directives. To disable implicit global using directives, remove the property or set it to false or disable.

Note that that means you don’t need using System; either.

Combined with top-level statements, your whole file could actually be:

List<string> list = new List<string>();
list.Add("List element.");
Console.WriteLine(list[0]);

Or if the namespace is important to you:

namespace testProgram;

List<string> list = new List<string>();
list.Add("List element.");
Console.WriteLine(list[0]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading