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;
// ...
}