Question Authors' Forum

Running C# in CodeRunner

Picture of Richard Lobb
Running C# in CodeRunner
by Richard Lobb - Friday, 6 October 2017, 8:43 PM

I received an email asking:

We use C# with our first year students and I was wondering if anyone has adapted Code Runner for C#.  If not would it take much time and effort to extend it.

I thought my answer might be of interest to others, so I'm posting it here ...

"If Mono is sufficient for your needs, you can run C# questions with the existing CodeRunner provided:

"I experimented a bit and came up with a C# program question type (i.e., a question that requires the student to write an entire program, which is run for each test case using the supplied stdin) as follows:

""" The template for a question type that compiles and runs a student-submitted
    mono C# program. 

import subprocess, sys

# Write the student code to a file prog.cs
student_answer = """{{ STUDENT_ANSWER | e('py') }}"""
with open("prog.cs", "w") as src:
    print(student_answer, file=src)

# Compile
return_code =['mcs', 'prog.cs'])
if return_code != 0:
    print("** Compilation failed. Testing aborted **", file=sys.stderr)

# If compile succeeded, run the code. Since this is a per-test template,
# stdin is already set up for the stdin text specified in the test case,
# so we can run the compiled program directly.
if return_code == 0:
        output = subprocess.check_output(["mono", "./prog.exe"], universal_newlines=True)
    except subprocess.CalledProcessError as e:
        if e.returncode > 0:
            # Ignore non-zero positive return codes
            if e.output:
            # But negative return codes are signals - abort
            if e.output:
                print(e.output, file=sys.stderr)
            if e.returncode < 0:
                print("Task failed with signal", -e.returncode, file=sys.stderr)
            print("** Further testing aborted **", file=sys.stderr)

Use this instead of the template for C-via-Python described at Also you need to set the Ace language to cs to get C# syntax colouring in the student answerbox.

Here's what a run of that question type looks like:

A C# write-a-program question

For other question types, such as "write-a-C#-method", you will have to wrap the student submission in some extra code, including that supplied in the {{TEST}} variable. If you need help with that, post back here.

I should mention that this question type has had minimal testing - it's provided only as a starting point to get you going.

If Mono is not sufficient for your needs, say because you need Microsoft libraries, then you're pretty much out of luck, unless you want to write your own sandbox.