Created: 4/24/2022
Things to watch out for in C#
- When using the
TPLlibrary, make sure that allasyncmethods return aTaskso that the caller has the ability toawaiton 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
dynamictypes 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
newing instances, make sure to check the metadata forIDisposableand, as applicable, use theusingclause 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,protectedandprivateappropriately, as well as thereadonlykeyword. - 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
defaultcase, 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, ortracein place of comments wherever possible. - Don't implement your own data-structures when .Net provides one.
- Avoid using of
tuples as your return type because it's not clear whatItem1andItem2represent. Instead define a class. If you're using later versions of C#, methods can return multiple values, make use of that.