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?
>Solution :
Look at your project file. I strongly suspect it will include this:
<ImplicitUsings>enable</ImplicitUsings>
The ImplicitUsings feature is described here:
The
ImplicitUsingsproperty can be used to enable and disable implicitglobal usingdirectives 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 addsglobal usingdirectives for a set of default namespaces based on the type of project SDK. Set this property totrueorenableto enable implicitglobal usingdirectives. To disable implicitglobal usingdirectives, remove the property or set it tofalseordisable.
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]);