Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to compile a struct [duplicate]

Tags:

c#

The following code suggests I cannot use implicit properties with a struct:

public struct LimitfailureRecord
{
   public LimitfailureRecord(string sampleCode)
   {
      SampleCode = sampleCode;
   }

   public string SampleCode {get; set;}
   {
   }
}

It fails to compile, with the error message

"Backing field for automatically implemented property 'blahblah.LimitfailureRecord.SampleCode' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer."

If I change the struct to a class it's fine. What do I need to do to make this work as a struct? I'd rather not go to the lengths of backing fields (this is a heavily stripped down version of the real code) if I can avoid it.

like image 683
haughtonomous Avatar asked Feb 17 '23 20:02

haughtonomous


2 Answers

With structs you have to call the default constructor in all other constructors:

public LimitfailureRecord(string sampleCode) : this()
{
    SampleCode = sampleCode;
}
like image 95
Martin Prikryl Avatar answered Feb 26 '23 21:02

Martin Prikryl


Use a constructor chaining like so:

public LimitfailureRecord(string sampleCode)
    : this()
{
    ...
}

The reason is the auto-implemented property introduces a (generated) instance field for backing, as described. All instance fields must be assigned to in an instance constructor of a struct.

Actually the error text you quote describes the fix pretty well.

Something else: If you keep the set accessor of your property public you will have a mutable struct. Most people agree that mutable structs should be avoided and are "evil" because their copy-by-value semantics and the possibility of mutating an existing struct value (as in record.SampleCode = "Here's a new string for an old object";) don't go well together. Check the threads on mutable and immutable structs.

like image 36
Jeppe Stig Nielsen Avatar answered Feb 26 '23 22:02

Jeppe Stig Nielsen