Best Practices

This is our definitive list of guidelines, suggestions, recommendations, etc
You can enable code analysis to enforce the rules you prefer.
You can also create an editorconfig so that Visual Studio automatically enforces your style guidelines.
As a starting point, you can copy the dotnet/docs repo's file to use our style.
link - learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2022
link - github.com/dotnet/docs/blob/main/.editorconfig


1) Use meaningful names starting with your solution and project name(s)

Solution 'ClassLibrary1' (1 of 1 project)  
  ClassLibrary1
    Properties
    References
    Class1.cs

Use Pascal Casing for Solutions, Projects, Files, Classes, Structures, Interfaces, Methods, Properties
Use camelCasing for local variables and method arguments.
Use UPPERCASE for constants.
Do not use any hungarian notation or abbreviations.
Class Names should be nouns, noun phrases or adjective phrases and should not contain an underscore.
Member Names should be verbs or verb phrases.


2) Use a very simple project structure, avoid nested sub folders and nested projects.

Solution 'ClassLibrary1' (1 of 1 project)  
  ProjectOne
    Forms
    Messages
  ProjectTwo

Avoid adding any dependencies unless absolutely necessary
Do not add any unnecessary comments
It is very common to put every class into its own file.
Add at least one blank line between method definitions and property definitions.
Avoid creating methods that perform multiple tasks
Namespace declarations should match the folder structure.


3) Use a consistent code formatting across all your applications.

?? 

Use four spaces for indentation. Don't use tabs.
Break long statements into multiple lines to improve clarity.
Avoid trailing whitespace
Write only one statement per line.


4) Always prefix with the full namespace to be explicit when referring to .NET classes and objects.

System.Collections.Generic.List<T> myCollection; 
MyNamespace.MyClass.MyObject myItem;

Qualify everything and organize your namespaces with a logical hierarchy.
Remove any 'using directives' unless they are absolutely necessary.


5) Always declare your variables at the top outside of the try-block.

string myText; 
try
{
}

When variables are declared at the top, debugging will be easier because the variables will never go out of scope and you can always mouse over to see the current value.
Avoid using any reserved words or names that are similar to object properties or methods.
A lot of developers suggest declaring variables just before they are used because this helps with refactoring.
In most cases though the refactoring never actually happens which results in the variables being a lot harder to find.
Always declare your class member variables and static variables (or fields) at the top of the class.


6) Avoid using the var implicit type for variables.

var customers = new System.Collections.Generic.Dictionary(); 
int lastIndex; // not System.Int32
bool isSaved; // not System.Boolean

Use the predefined type names instead of system type names like Int16, Single, UInt64, etc


7) Only use simple conditional branching syntax.

if (bvalue == true) 
{
}

Always include curly brackets and always put these on separate lines.
Do not use the Tenary Operator because it makes your code very hard to read and if you need to make changes, you will have to remove it altogether.
Avoid overly complex and convoluted code logic.


8) Add a try-catch to all your methods

try 
{}
catch (System.Exception ex)
{}

Never embed or nest try-catch statements
Use ex as the variable for a general exception
Use specific exception types to provide meaningful error messages.
Avoid empty catch blocks


9) When debugging change your Exception Settings to break on all exceptions.

(Debug > Windows > Exception Settings, "Common Language Runtime Exceptions") is checked. 

Selecting this checkbox will break the code whenever an exception is thrown, regardless of whether it is handled or not.


10) Always use Properties and not Public variables

public class Account 
{
    public static string BankName;
    public string Number { get; set; }

Declare all member variables at the top of a class, with static variables at the very top.
Group all the variables with the same data type together


11) Always use this. when accessing class member variables (esp private variables)
Prefix private member variables (or internal fields) with an underscore so they are not confused with the method parameters.

private string _myfield; 

12) Never use ref to pass arguments in to methods.

?? 

13) Use singular names for enumerations
do not explicitly specify a type of an enum or values of enums

public enum Color 
{
   Red,

The exception is for bit field enums.


14) Add suffixes and prefixes to improve readability.

public void Method_DoSomething(); 

Add the prefix "Method_" to all methods that are declared inside classes
Add the suffix "_Delegate" to any delegates
Add the suffix "_EventArgs" to any classes that extend System.EventArgs
Add the suffix "Exception" to any types that inherit from System.Exception
Add the suffix "Stream" to any types that inherit from System.IO.Stream
Add the suffix "en" to any enumeration types
Prefix private static variables with an underscore



15) When developing VSTO Add-ins use two projects.

Solution 'VSTOAddin' (2 of 2 projects)  
  DataRetriveProject
  ExcelDataRetrieve
    Excel
      ThisAddIn.cs
    Ribbon.cs
    Ribbon.xml

When there is only a single project the name if often the same as the solution.
Create a Class Library (dll) project for the actual code.
Create an Office specific project for the VSTO add-in.


16) When developing VSTO Add-ins use an alias directive for the corresponding application namespace.

using Excel = Microsoft.Office.Interop.Excel 
Excel.Workbook
Excel.Range



17) Always specify the access modifier, never rely on the defaults
private for member
internal for class


18) Avoid using String Interpolation

string displayName = $"{nameList[n].LastName}, {nameList[n].FirstName}"; 
string displayName = {nameList[n].LastName + nameList[n].FirstName;

19) Any public class members should only be accessible through Properties


Only use the same method name when it is overloaded (no duplicates across namespaces)
Using the same name with a different access modifier will work but is extremely confusing.


20) Always prefix interfaces with the letter I.
Interface names are noun (phrases) or adjectives.


21) Use Func<> and Action<> instead of defining delegate types


22) Use parentheses to make clauses in an expression apparent, as shown in the following code.


23) Null conditional Operator

var city = person?.Address?.City 

24) Instead of using "", use String.Empty


25) Always do null checks for objects


26) Windows Forms Controls
Do not change any of the properties in the designer.
Always change the properties in the code for more visibility.


27) Do not provide a default constructor for a structure ??


28) Use && and || (instead of & and |) when you perform comparisons
These are short circuit operators which means if the first operation is false, the second one will not be evaluated.


29) Do not use Lamdba expressions to define event handlers

public Form1() 
{
    this.Click += new EventHandler(Form1_Click);
}

void Form1_Click(object? sender, EventArgs e)
{
    MessageBox.Show(((MouseEventArgs)e).Location.ToString());
}


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext