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.
With structs you have to call the default constructor in all other constructors:
public LimitfailureRecord(string sampleCode) : this()
{
SampleCode = sampleCode;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With