Home > Mobile >  How to declare static instance globally in Program.cs of Console App .NET 6.0
How to declare static instance globally in Program.cs of Console App .NET 6.0

Time:04-30

I have created a console application .NET 6.0 for learning of Singleton Pattern. But I have observed a significant change in Program.cs file.

namespace, class and Main method have been removed from program.cs in .NET 6.0.

I believe the code that will be written in program.cs will be considered as within Main method. But I want to create two static methods which are using globally intialized instances but I am not able to do that.

By declaring the instances like below:

enter image description here

It gives Compile Error:

CS0106 The modifier 'static' is not valid for this item

While using the instances in static methods like below: enter image description here

It gives Compile Error:

CS8421: A static local function cannot contain a reference to 'tableservers1'.

Here is all the code of program.cs :

using SingletonApp;

static TableServers tableservers1 = TableServers.GetInstance();
static TableServers tableservers2 = TableServers.GetInstance();

Console.WriteLine("Hello, World!");

for (int i = 0; i < 5; i  )
{
    Host1();
    Host2();
}
Console.WriteLine();


static void Host1()
{
    Console.WriteLine("Host1 Next server is: "   tableservers1.GetNextServer());
}

static void Host2()
{
    Console.WriteLine("Host2 Next server is: "   tableservers2.GetNextServer());
}

Please someone can explain how can we use this new minified program.cs, specially to use global instance and variables and creating methods.

CodePudding user response:

As in this answer since C# 10 you can achieve this by introducing public partial class Program (at the bottom of you top level statement file or in separate file):

// rest of your top-level statement code 
// ...
public partial class Program 
{
    static TableServers tableservers1 = TableServers.GetInstance();
    static TableServers tableservers2 = TableServers.GetInstance();
}

But I would argue that switching to "old style" Program class or moving static fields to another class would be a better option.

  • Related