Search code examples
c#initializationstructurelocal

I can't initialize the internal structure with local variables C#


I honestly tried googling the answer but couldn't. Ok, i have a structure like this:

struct TestStruct 
        {   public int n;
            public struct _InnerStruct  {   public int m;   }   
            public  _InnerStruct InnerStruct;   
        }

And I can assign the value to some local variable in the n field:

static void  Main ()    
    {       
        int SomeLOCALvar = 1;
        TestStruct TEST_STRUCT = new TestStruct () { n = SomeLOCALvar };
    }

My problem is that I don't understand how to do exactly the same with the m field. Why doesn't code like this compile:

TestStruct TEST_STRUCT = new TestStruct () { n = SomeLOCALvar, .InnerStruct.m = SomeLOCALvar };

What would be the correct syntax?


Solution

  • Well, the following should work:

    TestStruct TEST_STRUCT = new TestStruct { n = SomeLOCALvar, InnerStruct = new _InnerStruct { m = SomeLOCALvar } };
    

    However, frankly it would be a very bad idea to do that. Value types (structs) should almost always be immutable; a struct with public mutable fields like this is incredibly brittle, and it will cause confusion and broken code.

    IMO, these should be readonly struct, with get-only properties, and constructors. For example:

    readonly struct InnerStruct {
        public int M { get; }
        public InnerStruct(int m) => M = m;
    }
    readonly struct TestStruct 
    {
        public int N { get; }
        public InnerStruct InnerStruct { get; }
        public TestStruct(int n, int m)
        {
            N = n;
            InnerStruct = new InnerStruct(m);           
        }
    }
    

    (they should also ideally both override Equals, GetHashCode and ToString, to prevent boxing)