3

I am trying to use a dll where the following structure exists:

 public struct MyStruct
 {
     public int Day;
     public int Hour;
     public int Month;
     public int MonthVal;
 }

In my code I am trying to assign values to these variables:

MyStruct MS; OR MyStruct MS = new MyStruct(); and then do
MS.Day = 1;
MS.Hour = 12;
MS.Month = 2;
MS.MonthVal = 22;

Problem is, MS cannot be assigned values, and because the struct has no constructor, I cannot do

 MyStruct ms = new MyStruct(1, 12, 2, 22);

So, how do I get values into the structure?

PeterJ
  • 364
  • 4
  • 17

1 Answers1

9

In my code I am trying to assign values to these variables

MyStruct MS = new MyStruct();
MS.Day = 1;
MS.Hour = 12;
MS.Month = 2;
MS.MonthVal = 22;

This approach works perfectly (demo). However, the two approaches described below are better:

If you do not want to define a constructor, this syntax would save you some typing, and group related items together in a single initializer:

MyStruct MS = new MyStruct {
    Day = 1,
    Hour = 12,
    Month = 2,
    MonthVal = 22
};

If you are OK with defining a constructor, do this instead:

public struct MyStruct {
    public int Day {get;}
    public int Hour {get;}
    public int Month {get;}
    public int MonthVal {get;}
    public MyStruct(int d, int h, int m, int mv) {
        Day = d;
        Hour = h;
        Month = m;
        MonthVal = mv;
    }
}

This approach would give you an immutable struct (which it should be), and a constructor that should be called like this:

MyStruct MS = new MyStruct(1, 12, 2, 22);
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @Moderator: I have a follow up question concerning constructor-less structs with a uint array: can I ask it here or do I start a new thread? – PeterJ Feb 09 '16 at 19:24
  • @PeterJ I am not a moderator, but the decision is up to you. If you think that your follow-up question does not change the substance of your original question, you are welcome to edit your question; however, as far as potential answers go, this is not likely to generate much new interest. On the other hand, if you think that your follow-up question is sufficiently different (say, it's more about embedding arrays into structs than about structs without constructors) then asking a new question is a better alternative. – Sergey Kalinichenko Feb 09 '16 at 19:30
  • @PeterJ I can tell you upfront that embedding arrays into structs is a rather questionable practice. – Sergey Kalinichenko Feb 09 '16 at 19:31
  • I fully accept that, but that is what I have to deal with in the dll I am forced to work with on this task. I will ask a new question then, thanks very much – PeterJ Feb 09 '16 at 19:34