Ayo Ijidakinro, Shift4 Manager, Payment Engineering

C# Coding Standards::Avoid Rolling Your Own Path Manipulation

Ayo Ijidakinro
2 min readJan 9, 2024

--

Sometimes I see code like this in a developer’s check-in:

someMergedPath = string.Format("{0}{1}", rootPath,fileOrDirectoryPathToAppend);

There are two problems with this.

#1: These days, C# code should use String interpolation instead of format strings

Format strings are not checked at compile-time and are thus prone to nasty run-time bugs because mistakes are easy to overlook.

#2: The .NET framework provides more robust path manipulation utilities than manually concatenating paths

Manual path concatenation is susceptible to trailing slash bugs — where the presence of a trailing slash, or lack thereof, causes problems.

Even if your code is implemented correctly on day one, a future developer may inadvertently cause a regression by making a change in upstream code. The change could invalidate the assumptions made by your hand-rolled path manipulation code.

Also, don’t be surprised when you yourself are the one who makes the inadvertent upstream change!

In fact, solid code practices protect the original developer almost as much as his teammates!

Use System.IO.Path or another reliable library

Ultimately, writing path manipulation code is not only unreliable, it’s also a waste of your time.

Your development time is better spent doing work with higher ROI.

Thus, rather than rolling your own path manipulation, use the path manipulation tools that are built into the .NET framework.

Something like:

someMergedPath = Path.Combine(rootPath,fileOrDirectoryPathToAppend)

Or, if you prefer, use a different 3rd party library that provides robust path manipulation. (Because, even Microsoft’s implementation has its own idiosyncrasies.)

In summary

If you’re writing code for yourself, it probably doesn’t matter what you choose.

But, if your code is going into a system that is customer-facing, do not roll your own path manipulation. Doing so makes your code brittle and is not a good use of your time.

Instead, for robust code that is reliable and easy to maintain, use .NET’s built-in path manipulation utilities in System.IO, or use a reliable 3rd-party library!

[If this article helped you, please hit the Clap and Follow buttons to help me write more articles like this.]

--

--

Ayo Ijidakinro

I’m a software engineer turned entrepreneur. Technology, SEO, and Marketing are my passions. Over the last 36-months my ads have made $1.36+ million in sales.