Warning on Unused Record Primary Constructor Parameter
See original GitHub issueI was recently playing with positional records and overriding the property declarations, e.g.:
public record Person(string FirstName, string LastName) {
public string FirstName { get; set; }
public string LastName { get; set; }
}
I was surprised to find that the constructor that is emitted in this case does not actually wire up the primary constructor parameters with the explicitly declared properties. I understand that this is because the implicit property declarations which are being overridden include an initializer which wires up the property.
In my opinion this would be an easy detail to miss and there is currently no indication that it’s happening. I think it would be useful if the compiler would warn (or otherwise indicate) when the primary constructor parameter is unused.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:13 (13 by maintainers)
Top Results From Across the Web
Rider wrongly reports a record type constructor parameter as ...
I have one abstract record type that takes one constructor argument. An inherited record type passes it from its own constructor.
Read more >C# 9 records validation
With the new record type of C# 9, how is it possible to inject a custom parameter validation/ null check/ etc during the...
Read more >Record structs - C# 10.0 draft feature specifications
A warning is produced if a parameter of the primary constructor is not read. The definite assignment rules for struct instance constructors ......
Read more >Hands on with Records in Java 14 – A Deep Dive
Adding annotations to record components ... If you pass a null value as the first parameter while instantiating record Car , you'll get...
Read more >Record types — Coq 8.17.1 documentation
In application form, all fields of the record must be passed, in order, as arguments to the constructor. Example: Constructing 1/2 as a...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
However, I would also see a ton of value in a general refactoring from a primary constructor to a regular constructor. I can see wanting to do this even when there are no current code issues.
(When records get validators, explicitly declared constructors might be less good.)
@Youssef1313 In that case I think the necessary change would be:
This is still in the territory of “The fix for this would be drastic enough that I wouldn’t really expect there to be a fix offered for this case” for me personally, as a Roslyn user.