Language Guidelines


Do use string interpolation to concatenate short strings

string fullName = $"{firstName} {lastName}";

Do use StringBuilder to append large strings

var messages = StringBuilder();
do 
{
    messages.AppendLine(exception.Message);
    exception = exception.InnerException;
} while (exception != null)

Do use implicit typing for local variables when the type is obvious

var name = "Matt";
var age = 21;

Do not use var when the type is not apparent. Do not rely on the variable name to specify the type

// correct
int result = CalculateFinalResult();
string location = GetLocation();

// avoid
var integerInput = Console.Readline();

Do use appropriate syntax when initializing arrays

// note the different when to use explicit type and `var`
string[] vowels1 = { "a", "i", "u", "e", "o" };
var vowels2 = new string[] { "a", "i", "u", "e", "o" };
var vowels3 = new string[5];

Do use try-catch for exception handling. Do not use it as a replacement of if-else conditional statement

// Avoid
try
{
    contents = File.ReadAllLines("log.txt")
} 
catch (FileNotFoundException)
{
    File.Create("log.txt");
}
catch (Exception ex)
{
    throw;
}

// Correct
try
{
    if (!File.Exists("log.txt"))
    {
        File.Create("log.txt");
    } else
    {
        contents = File.ReadAllLines("log.txt")
    }
} 
catch (Exception ex)
{
    throw;
}


Do not use try-finally as a replacement for using to call Dispose method

// Avoid
try
{
    fileStream = File.OpenRead("log.txt");
    ...
}
finally
{
    fileStream.Dispose(true);
}

// Correct
using (FileStream fileStream = File.OpenRead("log.txt"))
{
    ...
}