DEV Community

Cover image for 5 (Surgical) Tips to Program More Efficiently in C#💉
ByteHide
ByteHide

Posted on • Updated on • Originally published at bytehide.com

5 (Surgical) Tips to Program More Efficiently in C#💉

Writing efficient code isn't always easy, but it can be done. Here are five ways to program more efficiently in C#, no matter what your preferred programming environment is. Whether you use Microsoft Visual Studio or another IDE, this advice will help you quickly, easily, and efficiently improve your programming skills.

At first they may seem like very basic and absurd tips and advice but I know that many C# developers do not put them into practice and end up wasting much more time than expected just reading and trying to understand the code (and if that time has not come, it will come soon).

Most of all, though, these tips will help you save time and minimize errors along the way. In order to succeed at your job as a programmer, you need to make the most of your time - and these tips will help you do just that!


Take advantage of the record types

A very simple way to simplify your C# code when programming is to use record types. These provide a very easy to read way to create objects, especially in the immutable representation.

Bad way:

//A lot of code lines
public class ApplicationInfo
{
    public string Name { get; init; }
    public string Path { get; init; }
public ApplicationInfo(string name, string path)
    {
        Name = name;
        Path = path;
    }
}
Enter fullscreen mode Exit fullscreen mode

Good way:

 

//Only one line with record types
public record ApplicationInfo(string name, string path);
Enter fullscreen mode Exit fullscreen mode

This way you will save many lines of code and make it easier to read. If by chance in a few months you or another developer reads that code, you will understand it much easier.

📚Check out the Microsoft article to learn more: Create record types


Avoid poor object initialization

This is another practice that many developers overlook. If properties are not defined between braces, reading that code becomes difficult and this can lead to a longer time to understand that code.

Bad way:

//Poor code format for reading
Dotnetsafer securityManger = new Dotnetsafer();
securityManger.FindVulnerabilities = true;
securityManger.AppName = "Shield.exe";
Enter fullscreen mode Exit fullscreen mode

Good way:

//Better code format for reading
var securityManger = new Dotnetsafer { 
    FindVulnerabilities = true,
    AppName = "Shield.exe"
};
Enter fullscreen mode Exit fullscreen mode

In this case, as you can see, the solution is simple. Use object and collection initializers to allow a better reading of the code.

📚Check out the Microsoft article to learn more: Object and Collection Initializers


Get used to using Var to define variables

Developers often complicate ourselves by using types that are too specific when defining variables. This can only lead to confusion when it comes to understanding the code.

Bad way:

//Difficult to read
List<Repository.Shield.SecureDependencies> listOfSecureRefs = _repo.Shield.LastDependenciesAnalyzed();
Enter fullscreen mode Exit fullscreen mode

Good way:

//Easier to read
var listOfSecureRefs = _repo.Shield.LastDependenciesAnalyzed();
Enter fullscreen mode Exit fullscreen mode

To solve this bad practice, it is as easy as using var keyword. This way the final code will be cleaner and much faster to read.

📚Check out the Microsoft article to learn more: Implicitly typed local variables


String interpolation "$" instead string.Format()

String.Format() is a common method of inserting values from one string into another but it is not the cleanest or the best if we focus on clean code.

Bad way:

//using string.Format()
var date = DateTime.Now;
string greetings = string.Format("Today is {0}, the time is {1:HH:mm} now.", date.DayOfWeek, date);
Enter fullscreen mode Exit fullscreen mode

Good way:

//using string interpolation
var date = DateTime.Now;
string greetings = $"Today is {date.DayOfWeek}, the time is {date:HH:mm} now.");
Enter fullscreen mode Exit fullscreen mode

We see that by using string interpolation the resulting code is much more readable. This is an example with a very simple code. In much more complex real life cases, you will appreciate having the code organized and clean.

📚Check out the Microsoft article to learn more: $ - string interpolation


Null coalescing (??) instead if-else

At first glance, using nested if-else seems to be the simplest option for null checking. Although it is a simple option, it is not the best one.

Bad way:

if (application != null)
{
    if (application.protected != null)
    {
        return application.protected.shieldLastRun;
    }
    else 
    {
        return string.empty;
    }
}
else
{
    return string.empty;
}
Enter fullscreen mode Exit fullscreen mode

Good way:

return application?.protected?.shieldLastRun ?? string.empty;
Enter fullscreen mode Exit fullscreen mode

By using the null coalescing operator ?? we can greatly reduce the number of lines of code and make it easier to read.

📚Check out the Microsoft article to learn more: ?? and ??= operators

Top comments (5)

Collapse
 
mellen profile image
Matt Ellen

I thoroughly disagree about var. I have never seen an instance of using var where it wouldn't be clearer to state what the type of the variable is.

In your examples you don't explicitly type the DateTime but you do for the string which is a weird inconsistency.

Collapse
 
dumboprogrammer profile image
Tawhid

I agree.We don't need var

Collapse
 
scottctr profile image
Scott C.

If using var makes your code unclear, your method is too big or you have poorly named variables. With well named variables and everything in close proximity, the variable type should be obvious if needed. Besides creating cleaner code, using var also makes refactoring easier when changing the type is needed.

Collapse
 
dimitarbogdanov profile image
Dimitar Bogdanov

I haven't heard of a single C# developer that does not code in an environment that won't do refactorings for them. That's not a point.

As for making code unclear, I still disagree: having the type explicitly there is much better for readability. Calling methods from other libraries, as well as the same project, obviously sometimes results in the methods returning something. You have two options: figure out what the method returns, or write what the method returns once and then forget about it.

Migrations of third party libraries are also easier with explicit types. In case a type changes across versions (e.g. gets renamed), you can see the type's former name basically instantly, since it'll be highlighted as an error - it doesn't exist anymore. From then, using source control, you can see when and to what it was renamed. Same goes for properties, methods, etc.

Collapse
 
jessica_veit profile image
Jessica Veit

Perfect! Nothing to add here 😄