Refactor string manipulation in C#

This blog is maybe 'simple' for some and not even interesting to others but I'm hoping that blogging about this, it will sink in to my own head. 😁

Last week I had similar code to what I'm going to display and I refactored it with some prompting from my work mate. Today I had similar code but didn't realise how similar it was to last weeks code.

That annoyed me. I should have spotted the similarities.

Anyway, this blog, as I said, is hopefully going to help concrete this pattern in my head so I spot it in future.

Here is the code that needed refactoring:

 var areasOfInterest = string.Empty;

    if (model.AreasOfInterest != null)
                {
                    foreach (var aoi in model.AreasOfInterest)
                    {
                        areasOfInterest += aoi + ",";
                    }
                    areasOfInterest = areasOfInterest.TrimEnd(",");
                }

9 lines of code and all it does is creates a comma separated string.

This can be refactored down to a single line!

```

var areasOfInterest = model.AreasOfInterest != null ? string.Join(",", model.AreasOfInterest) : string.Empty;

```

It does the same as the 9 lines of code but this is tidier and I also don't need to do TrimEnd(",") because it won't add the rogue comma at the end.

Nice!

Published on : 01 November 2021