3

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;
    // ... 
}
11
  • 1
    Can you explain the use case of why you need a static constructor with a parameter? Commented Jul 30, 2018 at 9:22
  • 1
    please can you explain why you feel the need for a parameter on a static constructor.. if you read the info you will understand more why it wouldnt have one Commented Jul 30, 2018 at 9:22
  • 1
    I don't see the need for the firstBusNumber parameter. I also don't see the need for the globalStartTime field. Why it's initialized from the static constructor? This should be done from a method in your business logic(i.e. the first bus starts). Commented Jul 30, 2018 at 9:23
  • 2
    @Syrlia: then you should give this connection-object via normal constructor. You can use a singleton if desired(because it's same for all). Commented Jul 30, 2018 at 9:27
  • 1
    Who sais "never use a singleton"? That pattern exists for some reasons. Anyway everything is better the a static constructor - even a singleton. Commented Jul 30, 2018 at 9:35

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think you missunderstood my question. But your idea with a static init method is an acceptable solution. Thanks.
@Syrlia: but it's not a good solution for your original problem (inject a connection-object that is used by all instances). You want to avoid multi-threading issues, believe me. A singleton is a better approach
@TimSchmelter then what we can do? I run out of idea :(
@ThierryV: posting your real code in a new question would help.
0

Firstly your example is from Microsoft docs, you can read more [here]

You, can't create a static constructor in c#. If you want specific type behavior you opt to instance class. There is a workaround, you can create a static method that settings static members, but you will need remember to use it explicitly. Static relate to type itself. Ensure that your static constructor set static globalStartTime for this type once, it initializes the class before the first instance is created You should really rethink if you need a static construct with a parameter.

2 Comments

We discuss the need of a static constructor with parameter below my question. Your answer doesn't solve my question.
I understand that, but you notice that even the Microsoft engineer did not come up with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.