Instance Pattern - Enforce Instance Fields Similar to Interfaces #9204
-
The 'Instance Pattern' would be a kind of marker or contract much like an interface, but for instance fields, not methods. A declaration-only contract for instance fields, in the way that interfaces work for methods. This would allow us to enforce that certain fields exist without forcing a class into a rigid inheritance structure. Right now we can only use rigid inheritance or convoluted dependency injection to achieve something of this nature. Instance Patterns would allow a contract to be formed with a class that ensures the existence of specific instance fields. You could try to enforce this type of pattern with reflection, but that gets messy quickly. -See below franchyd recommends using interfaces with auto-properties rather than all this trouble! Thanks Franchy!
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 13 replies
-
What does this "instance pattern" do aside enforce that the marked class have said members? Can you use it as a type in it's own right? Can you use it as a generic type argument or a constraint? Can you have a variable of the pattern, and reference the fields through it? |
Beta Was this translation helpful? Give feedback.
Correct, fields are not considered part of the contract of a type. Per the .NET guidelines:
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/field
It's better to expose them as properties, which provides more flexibility and encapsulation.