A Single Bash Command To Simultaneously Run and Compile a CSharp (.cs) File

A Single Bash Command To Simultaneously Run and Compile a CSharp (.cs) File

Posted on December 5, 2019


Background: 2019 Advent of Code and Microsoft Troubles

I've started the 2019 Advent of Code for this December! (This will be my first one - don't know how I've missed it in previous years!) Anyway, to get better at C#, which I may be using in the future for work, I decided to do all the Advent challenges in C#.

That's when I realized I didn't know how to simply "run" a .cs script. With Python scripts we can simply use python, with Perl we have perl, and so on.

Of course anything to do with Microsoft is never straightforward :rolling_eyes:. Up till now, I had always just sat back complacently and let Visual Studio run the code for me simply via the 'run' button. But for these fun Advent scripts, I decided to just keep it simple with Visual Studio Code.

The Bash Alias

I wanted a simple way to simultaneously compile and run my C# scripts, saving me from having to issue giant, or worse, multiple Bash commands each time.

To achieve such a behavior we need just a few simple steps:

  1. First, we must allow our bash function to accept a single argument: the filename of the desired .cs file to compile and run.
  2. Compile that passed .cs file using csc, while also using the -nologo flag to suppress the annoying copyright and info that is normally posted.
  3. Execute the .exe file generated by csc.

Steps 2 and 3 will need to parse the filename argument separately such that csc operates on the .cs file, and mono operates on the generated .exe file.

I named my alias simply cs, since it will be used for .cs files exclusively. Here it is in its full 6 lines of glory:

# usage: cs <<FileName.cs>>
# output: any stdout as well as any effects produced from the executing the compiled C# script
function cs() {
    csc -nologo "${1%%.*}".cs;
    mono "${1%%.*}".exe;

I haven't tested it too extensively, but it's working for me as long as the script to be compiled has a static main method. (I think csc warns you or throws an error otherwise). Go ahead and copy that into your .profile, .bashrc, or similar, and get rippin' with C# scripts!

-Cheers! 🍺


Next / Previous Post:

Find more posts by tag:

-~{/* */}~-