Properties with separate types when referenced internally and externally #4371
Replies: 2 comments
-
private readonly List<string> _names = new();
public IEnumerable<string> Names => _names; Note: your pattern isn't safe here at all. A consumer can still cast the result back to a List and mutate it. |
Beta Was this translation helpful? Give feedback.
-
I don't think this use case warrants having a new form of auto-property. I just don't think it's common enough. Syntactically I don't think it makes sense to try to jam two members with different accessibility levels, different names and different types into a single member. And auto-properties also don't allow the class to access the backing field directly, except in the one very specific case of read-only auto-properties initialized within the constructor. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I find myself coding properties like so:
It would be nice if there were some way to combine the backing field into the property somehow, so that from a
public
context (outside the class) the property appears to beIEnumerable<string>
, but from aprivate
context (inside the class) it appears to beIList<string>
.I'm not sure what the syntax for this would look like, maybe someone has an idea?
Of course the external type of a property would have to be a supertype of the property's internal type (or maybe an implicitly convertible type?), if they're not the same; it wouldn't make sense to declare a
string
property that appears to be anint
from the outside!Beta Was this translation helpful? Give feedback.
All reactions