Consider the following code:
class C
{
public int A { get; set; }
public int B;
public C(int a, int b)
{
this.A = A; // Oops, bug! Should be `this.A = a`. No warning
this.B = B; // Oops, bug! Should be `this.B = b`. `warning CS1717: Assignment made to same variable; did you mean to assign something else?`
}
}
A
and B
are almost exactly the same thing, but one has a bug I will miss.
Is there a way I can get catch the first case at compile time?
EDIT: Some of the answers & comments want to explain to me that properties and fields aren't the same thing. I know that already. They explain why the compiler doesn't have a warning here; I get that. But I wrote a bug, and I don't like writing bugs. So my question is "How can I make sure I never, ever write this bug ever again?"
Potentially you could use a tool such as FxCop and write a custom rule using VisitAssignmentStatement:
Some examples:
Example1
Example2
This isn't cast-iron, but if you installed ReSharper and set its inspection for 'Unused parameter' to 'Error', and further turned its Solution-Wide Analysis on, you'd see this in the code window:
One of these red indicators over in the right margin:
And this down in the status bar:
Which together make a combo that as a ReSharper user you'd soon become unable to ignore :)
Wouldn't stop you compiling, though.
Jay,
A great question. I believe most of the points which are relevant have been covered in various responses, but just to summarise:
Whilst potentially not the answer you were after, I think #3 is the most important point here. Naming items properly is the single most effective solution. Not only that but people might not have the luxury of relying on ReSharper and other such tools.
To that end I'd also recommend StyleCop. It can be a little invasive, but it is a great tool for helping a developer, or team of developers, adhere to a set of syntax conventions which you'll find will pretty quickly eradicate bugs such as the one you've highlighted.
Happy coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With