The using scope ends at the end of the method.
The c# 8 metod:
internal class Program
{
static void Main(string[] args)
{
using Program p = new();
Console.WriteLine("Hello World!");
} // <-- using scope ends here
}
Is just a shortcut for writing:
internal class Program
{
static void Main(string[] args)
{
using (Program p = new())
{
Console.WriteLine("Hello World!");
} // <-- using scope ends here
}
}
If you want to get out of the using scope you will need to use braces in some way.
You could use the braces like this instead, but I'm not sure what the advantage of that would be.
internal class Program
{
static void Main(string[] args)
{
{
using Program p = new();
Console.WriteLine("Hello World!");
} // <-- using scope ends here
Console.WriteLine("Out of scope");
}
}
Or extract it to a new method
internal class Program
{
static void Main(string[] args)
{
ExtractedToMethod();
Console.WriteLine("Out of scope");
}
static void ExtractedToMethod()
{
using Program p = new();
Console.WriteLine("I'm in scope");
} // <-- using scope ends here
}