To cut a long story short: I find the Java antipatterns an indispensable resource. For beginners as much as for professionals. I have yet to find something like this for C#. So I'll open up this question as community wiki and invite everyone to share their knowledge on this. As I am new to C#, I am strongly interested in this, but cannot start with some antipatterns :/
Here are the answers which I find specifically true for C# and not other languages.
I just copy/pasted these! Consider throwing a look on the comments on these as well.
NullReferenceException
Throwing the wrong exception:
if (FooLicenceKeyHolder == null)
throw new NullReferenceException();
Public variables in classes (use a property instead).
Unless the class is a simple Data Transfer Object.
if (myBooleanVariable == true)
{
...
}
or, even better
if (myBooleanVariable != false)
{
...
}
Constructs like these are often used by C
and C++
developers where the idea of a boolean value was just a convention (0 == false, anything else is true); this is not necessary (or desirable) in C# or other languages that have real booleans.
using()
Not making use of using
where appropriate:
object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close. Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away. 2. C# is GC so this doesn't do what was intended anyway.
Rethrowing the exception incorrectly. To rethrow an exception :
try
{
// do some stuff here
}
catch (Exception ex)
{
throw ex; // INCORRECT
throw; // CORRECT
throw new Exception("There was an error"); // INCORRECT
throw new Exception("There was an error", ex); // CORRECT
}