DEV Community

Cover image for 5 easy tips for writing C# better
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

5 easy tips for writing C# better

Even if you are late with the project timeline or due date, it's important to write good code.
Writing code is not easy and this is the reason why you have to write a more readable and elegant code as you can.

Let's see some small syntax tips.

1. Reduce lines of unuseful code

Bad

public ActionResult Index()  
{  
    return View();  
}  
Enter fullscreen mode Exit fullscreen mode

Good

public ActionResult Index() => View();
Enter fullscreen mode Exit fullscreen mode

OR

Bad

if (!string.IsNullOrEmpty(yourVar))  
{  
    //your code  
} 
Enter fullscreen mode Exit fullscreen mode

Good

if (yourVar is { Length: > 0 })
{
    //your code
}
Enter fullscreen mode Exit fullscreen mode

2. Primitive data type validation

Avoid custom method to validate primary type. 99% of primary types has their own validation type.

public bool CheckIfIsNumberic(string value) => int.TryParse(value, out int _);
Enter fullscreen mode Exit fullscreen mode

3. Use conditional operator

When possible, to improve the readability of the code, use the ternary condition.
They help to read the code after a long period.

Bad

public static string CheckFirstName(User user)
{
    var defaultFirstName = "Default";

    if (user.Name != null)
    {
        return user.Name;
    }
    else
    {
        return defaultName;
    }
}
Enter fullscreen mode Exit fullscreen mode

Good

public static string CheckFirstName(string name) => name ?? "Default";
Enter fullscreen mode Exit fullscreen mode
  1. Naming Conventions Find your rules and be consistent in every projects. Simple name for a single object, add the suffix List for multiple objects.
var item = new Item();
var items = new List<Item>();
Enter fullscreen mode Exit fullscreen mode
var item = new Item();
var items = new List<Item>();
Enter fullscreen mode Exit fullscreen mode

Try to follow the table below:

5. Optimizing Queries with LINQ

LINQ is very powerful to query objects in C# but it should be a bottleneck about the performances or, maybe in the worst case, for readability.

This code works, but try to take a look to the best version below this one

public List<Article> GetArticlesByPrice(double price)
{
    var articlesList = new List<Article>();

    foreach (Article article in Articles)
    {
        if (article.Price< price)
        {
            articlesList.Add(article);
        }
    }

    return articlesList;
}
Enter fullscreen mode Exit fullscreen mode

This is better:

public List<Article> GetArticlesByPrice(double price)
{
    var articlesList = new List<Article>();

        IEnumerable<Article> lambdaArticles = Articles.SelectMany(c => c.Articles).Where(p => p.Price < 100);
    articlesList  = lambdaArticles.ToList();

        return articlesList;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Feel free to share your tips in the comments and I will update my blog!

Discussion (4)

Collapse
n3wt0n profile image
Davide 'CoderDave' Benvegnù

I agree with everything, except this:

if (yourVar is { Length: > 0 })
{
    //your code
}
Enter fullscreen mode Exit fullscreen mode

I think the other way to write code with the !string.IsNullOrEmpty(yourVar) is much clearer and easier to read.

Good code doesn't always mean the same thing, and I think writing "better" code also means having higher readability for everyone, from junior devs up.

IMHO, of course :)

Collapse
kasuken profile image
Emanuele Bartolesi Author

you know what? For me it's more easy to read this line of code.
At the beginning I agreed with you... but now I prefer the "new" version.

and of course... everyone can have different opinions

Collapse
mteheran profile image
Miguel Teheran

Regarding number 1. I prefer the first option instend of evaluate a property

if (!string.IsNullOrEmpty(yourVar))

{

//your code

}

in C# 8, we can use the operator (?) to evaluete if the string is null or not

Collapse
turry profile image
Turry

Starting to learn C#, hope it comes useful.