1

I have this snippet of code. Why does C# know what Path class is without giving me an error given that Path is in the System.IO, logically, I should include it. However, Visual Studio 2022 did not yell at that. And another question is does using Some.Namespace automatically import other files in the file structure in C#? Like in PHP, when we want to use some classes from another file, we have to import that file use require_once or in Python, we use the import statement.

using System.Text.Json;

namespace ContosoCrafts.Website.Services
{
    public class JsonFileProductService
    {

        public JsonFileProductService(IWebHostEnvironment webHostEnvironment)
        {
            WebHostEnvironment = webHostEnvironment;
        }

        public IWebHostEnvironment WebHostEnvironment { get; }

        private string JsonFileName
        {
            get { return Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json"); }
        }
    }

}

1 Answers1

0

.NET 6 has introduced somthing called implicit global usings. You can read more about it in Scott Hanselman's blog post

https://www.hanselman.com/blog/implicit-usings-in-net-6

TWong
  • 91
  • 2
  • 5
  • Does using Some.Namespace automatically imports other files in the file structure in C#? Like in PHP, when we want to use some classes from another file, we have to import that file using require_once or in Python, we use the import statement. – Đạt Phạm Nguyễn Ngọc Sep 06 '22 at 13:48
  • In the above example, the using only imports a namespace for usage in that class. It's not a global using. I would direct you to https://stackoverflow.com/questions/9023465/importing-nested-namespaces-automatically-in-c-sharp for a pretty detailed answer. – TWong Sep 07 '22 at 14:27
  • Just to clarify, global usings only started with .NET 6 (C# 10) - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive. That's probably what you're looking for as someone who's coming over from PHP. – TWong Sep 07 '22 at 15:57