Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Constructor With Parameter

I've read this thread "When is a static constructor called in C#" including the Programming Guide.

But is there any way to use a static constructor WITH a parameter?

I see the problem, that the static constructor is invoked bevor the first instance is created. I search for any smart solution/workaraound.

Here an example:

public class Bus
{
    protected static readonly DateTime globalStartTime;
    protected static readonly int FirstBusNumber;

    protected int RouteNumber { get; set; }

    static Bus(/*int firstBusNumber*/)//Error if uncomment: The static constructor must be parameterless
    {
        //FirstBusNumer = firstBusNumber;
        globalStartTime = DateTime.Now;
        Console.WriteLine($"The First Bus #{FirstBusNumber} starts at global start time {globalStartTime.ToLongTimeString()}");
    }
    public Bus(int routeNum) 
    {
        RouteNumber = routeNum;
        Console.WriteLine($"Bus #{RouteNumber} is created.");
    }
    public void Drive()
    {
        var elapsedTime = DateTime.Now - globalStartTime;
        Console.WriteLine("{0} is starting its route {1:N2} minutes after the first Bus #{2}.",
           RouteNumber,
           elapsedTime.TotalMilliseconds,
           FirstBusNumber
        );
    }
}

...

var bus1 = new Bus(71);
var bus2 = new Bus(72);

bus1.Drive();
System.Threading.Thread.Sleep(25);
bus2.Drive();

System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

Notice: Following code is not an acceptable solution.

public Bus(int routeNum)
{
    if (FirstBusNumber < 1)
       FirstBusNumber = routeNum;
    // ... 
}
like image 411
Syrlia Avatar asked Jul 21 '26 19:07

Syrlia


1 Answers

As per MSDN,

A static constructor is called automatically to initialize the class before the first instance is created. Therefore you can't send it any parameters.

But you can create a method static to init your static values.

Check fiddle https://dotnetfiddle.net/4fnahi

public class Program
{
    public static void Main()
    {
        Bus.Init(0);
        Bus bus1 = new Bus(71);
        Console.WriteLine(Bus.FirstBusNumber); // it prints 71 as your expected
    }
}

public class Bus
{
    public static int FirstBusNumber;

    public static void Init(int firstBusNumber) => FirstBusNumber = firstBusNumber;

    public Bus(int routeNum)
    {
        if (FirstBusNumber < 1)
           FirstBusNumber = routeNum;
    }
}
like image 143
Antoine V Avatar answered Jul 24 '26 09:07

Antoine V