I'm having a dilemma with Get-Only props vs readonly
after we can assign Get-Only right away like this string X { get; } = "dd"
.
So the question is: Why do we ever want to favour using readonly
field in a class
after C# 6 instead of using Get-Only property?
We can do this:
EX 1.
private readonly IService _service;
public A(IService service)
{
_service = service;
}
BUT we can also do this:
private IService _service { get; }
public A(IService service)
{
_service = service;
}
Both scenarios can only be initialized in ctor and can be used only within a class.
We can do those (from ctor as well):
EX 2.
private string SomeString { get; } = "s";
private readonly string SomeString2 = "s";
I cannot inherit readonly
field but I can inherit Get-Only prop, which might be confusing to distinguish from the inherited prop but only when you have a capital naming convention for private props, if you use _prop
you are fine. So more flexibility here.
We can also have:
EX 3.
public readonly string Field;
public string Field2 { get; }
And those are working the same except for minor thing for dev awareness - he cannot tell on the spot if the Field2
was not inherited.
I used to write DTO's like this:
EX 4.
public class DTOProp
{
public string Field1 { get; }
public string Field2 { get; }
public string Field3 { get; }
public DTOProp(string field1, string field2, string field3)
=> (Field1, Field2, Field3) = (field1, field2, field3);
}
Currently like this
public record DTORec(string Field1, string Field2, string Field3);
But never seen like this:
public class DTORo
{
public readonly string Field1;
public readonly string Field2;
public readonly string Field3;
public DTORo(string field1, string field2, string field3)
=> (Field1, Field2, Field3) = (field1, field2, field3);
}
We can write the hypothesis for readonly
fields that can look like that -
When You use C# 6+ You can safely replace readonly
fields with Get-Only properties with no side effects
and it seems completely valid to me.
After we replace the readonly-ies
we end up with a more predictable way of writing a code without losing the meaning of the code and well as changing the behaviour.
I understand that the backing field will be created and it might have some performance impact but to optimize the application to that point we will probably have 99% more important issues in other places. The only thing that might be an "issue" is the problem I mentioned in EX 3 but it probably evens out with time to respond to a PR comment "why not Get-Only prop here?".
PS. Tried to find a similar question. Didn't actually find the answer I was looking for