-4

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?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
NESHOM
  • 899
  • 16
  • 46
  • 2
    `new SWExecutionTime()` only instantiates the struct; it does not create a new stopwatch object within the struct. If you want to do that, write a constructor for the struct, or provide a default instantiation. – Robert Harvey Oct 13 '15 at 21:12
  • constructor with array? why downgrade? – NESHOM Oct 13 '15 at 21:13
  • 2
    I have no idea what that means. Without some sort of construction, there's no hope of having a stopwatch object in there. Remember, `int` and `double` are primitive types; the compiler can assume a default value of zero for them. The same is not true of the StopWatch class. – Robert Harvey Oct 13 '15 at 21:14
  • 2
    Alternatively, use a `class` instead of a `struct`. Then you can write your parameterless constructor without the compiler complaining. – Robert Harvey Oct 13 '15 at 21:16

1 Answers1

3

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.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112