Can I force the use of 'this' keyword in c# .NET?

You can fix this simply by enabling "Treat warnings as errors":

Warning 2 Assignment made to same variable; did you mean to assign something else?

(CS1717 if you want to enable it just for this one)

The compiler already tells you about this; you should be reviewing the warnings (and aim for zero warnings).

Re the middle one being unclear:

Foo = foo;

I disagree - that is perfectly clear to me (unless you come from a VB background and have developed case-blindness).


No, you can't change the behaviour of the language like this. If you use ReSharper I believe you can tell it to flag up this sort of thing - it may not come up in the error list, but in the margin and in an "indicator light" for the overall file health.

I personally don't tend to lose too much sleep over this sort of thing, as it's usually obvious as soon as you test - I can only recall one scenario where it's really bitten me, which was when I ended up with a stack overflow (not exactly the same situation, but again a casing issue) within a type initializer, running on Windows Phone 7 - a mixture of difficult debug environments, basically.


You can use StyleCop to generate a warning if you do not prefix with this. You can get StyleCop to run as part of the build process by following these these instructions

StyleCop comes with a bunch of default rules, many of them terrible, but you can edit your rules file to make the most sense for your developers. You can also share the StyleCop file so changes are immediately replicated to all your developers.

Its a fairly nice solution, free, provided by Microsoft and if you come up with a suitable rule set then your developers will create much "neater" code. You can also create custom rules along the lines of "Methods shouldn't be too long" where you define the length. Plenty of things to play with.

Also I guess you could set warnings as errors, but if you do make sure your StyleCop settings are exactly as you want them.