Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct without constructor [closed]

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?

like image 933
PeterJ Avatar asked Oct 30 '25 13:10

PeterJ


1 Answers

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);
like image 90
Sergey Kalinichenko Avatar answered Nov 02 '25 03:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!