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