Tips For .NET Programmers

Today I am going to share some tips for Dot Net programmers and using C# as main reference language, hope these tips can be helpful to get performance and maintain code standards:

  • Always try to use “using block” with critical and expensive resource like connection, stream and etc. If it is not possible to use using block then explicitly call close/similar method.

  • If any generic is not useful or local instances of generics is going out of scope then explicitly call clear for that item.

  • Please consider catch block to handle unexpected or uncontrolled flow. It is always advisable to avoid exception. For example, try to check divide by zero instead of handling it in catch block.

  • Depending on application structure and requirements, we may perform required actions and then may bubble up exception using “throw” statement instead of “throw ex”;

  • We may implement logging for exception.

  • It is highly recommended to decompose a function or method if it is exceeding the visible screen. Rule of thumb is any function should be visible without vertical scroll.

  • We may prefer to make helper classes to perform specific set of operations like: file writing, data converter and etc.

  • Try to avoid value assignment to enum members until unless, these are flagged enums or may have specific purpose like association with database value.

  • Get latest before Check in and make sure that code is compliable before and after check in.

  • Always remove unused namespaces (Context Menu -> Organize using -> Remove and Sort).

  • It is preferable to reformat code (in Code View using Ctrl + K + D).

  • Use conditional expression in Single, First or FirstorDefault with collection when single item is required.

  • If more than one property is required from a collection object then get that object once from collection, instead of using search for each property.

  • Use Constants or Enums instead of hardcoded values.

  • Use string.Empty instead of “”.

  • If catch does not use Exception object then it is better to omit declaration of Exception.

  • Define required variable at top of scope.

  • Arrange code in regions.

  • Please avoid spelling mistakes.

  • If some item is output of processing and is only required in specific block then better to perform the processing in that block.

  • Remove commented code and unused variables.

  • There should not be any dead or unreachable code sections.

If you are working in C#, then I may recommend you to go through the following articles by Microsoft:


Similar Articles