DI and hypothetical readonly setters in C#
Posted
by
Luis Ferrao
on Programmers
See other posts from Programmers
or by Luis Ferrao
Published on 2012-10-12T12:42:23Z
Indexed on
2012/10/12
15:48 UTC
Read the original article
Hit count: 355
c#
|dependency-injection
Sometimes I would like to declare a property like this:
public string Name { get; readonly set; }
I am wondering if anyone sees a reason why such a syntax shouldn't exist. I believe that because it is a subset of "get; private set;", it could only make code more robust.
My feeling is that such setters would be extremely DI friendly, but of course I'm more interested in hearing your opinions than my own, so what do you think?
I am aware of 'public readonly' fields, but those are not interface friendly so I don't even consider them. That said, I don't mind if you bring them up into the discussion
Edit
I realize reading the comments that perhaps my idea is a little confusing. The ultimate purpose of this new syntax would be to have an automatic property syntax that specifies that the backing private field should be readonly. Basically declaring a property using my hypothetical syntax
public string Name { get; readonly set; }
would be interpreted by C# as:
private readonly string name;
public string Name
{
get
{
return this.name;
}
}
And the reason I say this would be DI friendly is because when we rely heavily on constructor injection, I believe it is good practice to declare our constructor injected fields as readonly.
© Programmers or respective owner