Introduction
In this article, we will cover Common mistakes and how to avoid them with C#.
So, Let's get started.
C# is a strongly typed language with many cool features to help us develop software with greates ease. We can however still make mistakes and many of them are quite common.
Here are common C# mistakes that are often made and how to avoid them!
Stop checking null with the if statement
The if statement can have an enormous number of utilities and uses. One of them is to use it to check null. Although this is the correct way, it can be stated a little better.
Avoid this
if(result != null)
{
if(result.data != null)
{
return result.data.appRun;
}
}
Try this
return result?.data?.appRun;
Use Tuples instead of classes
If you want to return more than one result, the first thing that will probably come to mind is to create a class just for that purpose. This is the correct way to do it but not the best way to do it.
Avoid this
public ResultInfo GetInfo()
{
var result = new ResultInfo
{
Path = "C:/desktop/vyelve/Test",
Name = "Result.exe";
};
}
Try this
public (string path, string name) GetApplicationInfo()
{
return ("C:/desktop/vyelve/Test","Result.exe");
}
Usage of String Concatenation
Avoid this
var values = new List<string>() {"Hello ", "C# ", "Corner", "!"};
string outputValue = string.Empty;
foreach(var value in values)
{
outputValue += value; // Creates a copy of the string in memory
}
Console.WriteLine(outputValue);
Try this
var values = new List<string>() {"Hello ", "C# ", "Corner", "!"};
StringBuilder outputValueBuilder = new StringBuilder();
foreach(var value in values)
{
outputValueBuilder.Append(value);
}
Console.WriteLine(outputValueBuilder);
Incorrect Evaluation of the Default value for uninitialized variables
Avoid this
public class Program
{
static Point point;
static Pen pen;
public static void Main(string[] args)
{
Console.WriteLine(pen == null); // True
Console.WriteLine(point == null); // False
}
}
Try this
public class Program
{
static Point point;
static Pen pen;
public static void Main(string[] args)
{
Console.WriteLine(pen.IsEmpty);
Console.WriteLine(point.IsEmpty);
}
}
Don't use Throw ex
Avoid this
catch(SomeException ex)
{
logger.log(ex);
throw ex;
}
Try this
catch(SomeException ex)
{
logger.log(ex);
throw;
}
Using T Casting
Avoid this
var man = (Man)person;
Try this
var man = person as Man;