string.Join Extension Method

April 19, 2018 .net c# linq

Normally if want to do a string.Join on the result of a Linq query you end up with somthing looking like this:

Console.WriteLine(string.Join(", ", numbers.Where(x => x % 2 == 0)));

The call to string.Join has to come first and then the Linq query. I've always felt this breaks the flow of the code and would be easier to read if the string.Join was at the end of the Linq query:

Console.WriteLine(numbers.Where(x => x % 2 == 0).JoinString(", "));

This can be implemented with the following extension methods:

public static class JoinStringExtensions
{
    public static string JoinString<T>(this IEnumerable<T> source, string seperator) =>
        string.Join(seperator, source.Select(x => x.ToString()));

    public static string JoinString(this IEnumerable<string> source, string seperator) =>
        string.Join(seperator, source);
}

The specialization for IEnumerable<string> is just mirroring the implementation from string.Join.

Run a program directly after building in VS Code

Whenever I have a program that is just a generator of some kind I like to have that program execute directly after having built the program successfully. I'm going to show how to run the program via the dotnet cli but this trick can easily be applied to regular .NET programs or any program which is built using MSBuild.

Read More

Merging Build.Directory.props

April 04, 2018 msbuild .net

MSBuild version 15 introduced the concept of "Directory.Build.props" files. From the docs:

  • Directory.Build.props is a user-defined file that provides customizations to projects under a directory. This file is automatically imported from Microsoft.Common.props unless the property ImportDirectoryBuildTargets is set to false.

What is not stated here is that only one Directory.Build.props will be imported automatically. Imagine your project exists in the directory C:\repo\src\foo\foo.csproj and there exists a file in both C:\repo\src\Directory.Build.props and C:\repo\Directory.Build.props then only C:\repo\src\Directory.Build.props will be automatically included when building C:\repo\src\foo\foo.csproj. If you would like C:\repo\Directory.Build.props to be included as well, then C:\repo\src\Directory.Build.props will have to include C:\repo\Directory.Build.props like so:

<Project>
    <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
</Project>

This is documented here.

Git Quick Push

March 29, 2018 git batch

Here's a quick one liner to quickly stage all your changes in the current git repo, commit them and then push the commit to origin master branch.

Read More

Poor Man's Template Engine in C# Part 3

Include

In our last episode we implemeted the first two helper funcitons HtmlEncode and If. Today we want to implement Include.

Read More