this post was submitted on 29 Oct 2024
5 points (85.7% liked)

C Sharp

1537 readers
1 users here now

A community about the C# programming language

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

founded 2 years ago
MODERATORS
 

Well written thoughts on C#12 primary constructors. Sadly they are not really useful. At least for now.

you are viewing a single comment's thread
view the rest of the comments
[–] GetOffMyLan 1 points 1 month ago (1 children)

They're great for service dependencies. Just removes a lot of boilerplate.

[–] Mihies 1 points 1 month ago (1 children)

Yes, but not really, because those are not readonly as they should be.

[–] GetOffMyLan 1 points 1 month ago (1 children)

Does that really matter though? It's a minor issue and it's very unlikely any one would try to assign to a dependency.

If it really matters to you declare read-only fields and assign them. You still cut out all the lines for constructor assignments as the field assignments take the same amount of space.

[–] Mihies 1 points 1 month ago

Yep, I know I could assign those manually to readonly fields or such. But then I don't profit much and also risk of field duplication (as described in article). Also I use CodeRush to auto generate constructors for me (after manually typing all readonly fields) - that way I have less typing to do than using primary constructors. I guess CodeRush could do it the other way round as well, but still, there is problem with duplication at least. I don't know, perhaps is subjective, but I'm avoiding primary constructors for now.