I have a simple Factory implementation in my code. I’m aiming to have the constructed objects retain a reference to the factory that created them, so I have them wired up similar to this:
public class Factory {
public T CreateObject<T>() where T : Foo, new()
{
return new T() {
parent = this
};
}
}
public class Foo {
internal Factory parent;
internal Foo() { }
}
This works as it reads, but I’ve been thinking that I probably want that parent variable so that it cannot be changed once it’s set by the factory. However, if I declare it like internal readonly Factory parent;, then the factory can’t set it’s value anymore on construction.
I’d normally remedy this by providing a parametered constructor, but that kills the generic implementation, because AFAIK where T : new() implies a parameter-less constructor.
I may just be missing a few cogs with my C# chops, but what would be the best way to go about implementing something like this? (Or would it be better to just ditch the readonly and trust that the code won’t be modifying parent in an unsafe manner — NullReferenceExceptions come to mind — ?)
I do not think you can obtain exactly what you want, but you could make a property that is only assignable once and let the factory overwrite it. But I guess the user can always force an override with
new CreatingFactory, but I think this makes it difficult and at least clearly shows your intention.You could do something like below.
After having created it i searched and found an answer that is probably better than mine: Is there a way of setting a property once only in C#