I know there's a pattern involving partial classes to implement a class that has settable properties to the assembly, but is read-only from the outside, something like
// This is just the non-working example to get the idea of what I want it to do across
public interface IMyReadable
{
int Property1 { get; }
string Property2 { get; }
}
internal interface IMyEditable : IMyReadable
{
int Property1 { get; set; }
string Property2 { get; set;}
}
public class Implementation : IMyEditable
{
public int Property1 { get; internal set; }
public string Property2 { get; internal set;}
}
since you can't define 'internal set' in an interface. It can be implemented for classes as e.g. https://stackoverflow.com/a/42082500/6155053
…but what if I want to do this for structs?
I know, structs should be completely read-only usually, but it would be nice to have multiple different struct implementations implementing the interface, and then being able to instance them first and init them property by property afterwards from inside the assembly, e.g. in a factory class, without having to write the setting for each of the interface's properties out for each different implementation (via their c'tors or something).
That would allow me to do something like
// non-sense, but explanatory code snippet
[…]
var structs = new HashSet<IMyEditable>();
structs.Add(new MyEditableImplementation1());
structs.Add(new MyEditableImplementation2());
structs.Add(new MyEditableImplementation3());
int i = 0;
foreach(IMyEditable s in structs)
{
s.Property1 = ++i;
s.Property2 = i.ToString();
}
// ...and still be able to set custom properties only some of the implementations
// have afterwards, etc., and when you then return, for example do:
return structs.Cast<IMyReadable>();
Would save writing a lot of boilerplate for initialization as the number of implementations of the interface increases.
However, since structs are always sealed and can't inherit from a "base struct"… how would I do this without losing the advantage of auto-implemented properties (which I would if I'd do it with proxy properties with shared private fields inside every struct—that, again, means a lot of boilerplate code, only in another place).
Is this possible? If so, how?
Edit: Added 2nd sample to explain desired usage