Created: 4/24/2022
Things to watch out for in C#
- When using the
TPL
library, make sure that allasync
methods return aTask
so that the caller has the ability toawait
on it. - When writing property getters, be careful with case sensitivity of the property name and the internal backing field in order to avoid an infinite recursion and stack overflow.
- Avoid using
dynamic
types as they bypass the strong-typing and all of its compile-time benefits and incur runtime performance hits. - Use the facilities offered by the language, such as safe null-coalescing and null-conditional operators.
- When
new
ing instances, make sure to check the metadata forIDisposable
and, as applicable, use theusing
clause for automatic disposing of the generated classes even in the case of an exception. - Be knowledgeable about LINQ and use proper overloads.
- Use OOP concepts wisely. Describe intent using the method modifiers
public
,protected
andprivate
appropriately, as well as thereadonly
keyword. - For all public methods, check the validity of the argument.
- Be consistent with error handling, use correct exception types.
- Avoid catching generic exceptions as those can hide real programming errors.
- Adopt a coding style (or your team's coding style) and stick to it for better readability and maintainability of the code.
- When writing switch statements, consider the
default
case, even if it's not valid. For switches on enum values, having a default case that throws as applicable will future-proof the code in case more values are added to the enum. - Prefer
assert
,debug
, ortrace
in place of comments wherever possible. - Don't implement your own data-structures when .Net provides one.
- Avoid using of
tuple
s as your return type because it's not clear whatItem1
andItem2
represent. Instead define a class. If you're using later versions of C#, methods can return multiple values, make use of that.