Search code examples
c#structstopwatch

Structs cannot contain explicit parameterless constructors


I'd like to define a struct that includes StopWatch and then an array of struct.

    struct SWExecutionTime
    {
        public Stopwatch swExeTime;
        public int intSWRecCount;
        public double dblSWResult;
    }

    SWExecutionTime[] SWExeTime = new SWExecutionTime[10];

It shows run-time error System.NullReferenceException when I try to do this:

    SWExeTime[0].swExeTime.Start();

The initial value of intSWRecCount and dblSWResult are zero, so I don't need to have a constructor to initialize these variables. The only variable that needs initialization is swExeTime (apparently). C# also shows the error Structs cannot contain explicit parameterless constructors when I use constructor without any input parameter.

How can I fix this?


Solution

  • Use a class, why are you stuck on structs?

    class SWExecutionTime
    {
        public Stopwatch SWExeTime { get; } = new Stopwatch();
        public int SWRecCount { get; } = 0;
        public double SWResult { get; } = 0;
    }
    

    Also, follow best practices for naming.