Question Authors' Forum

Running C# in CodeRunner

Running C# in CodeRunner

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
with open("prog.cs", "w") as src:

# Compile
return_code = subprocess.call(['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:
try:
output = subprocess.check_output(["mono", "./prog.exe"], universal_newlines=True)
print(output)
except subprocess.CalledProcessError as e:
if e.returncode > 0:
# Ignore non-zero positive return codes
if e.output:
print(e.output)
else:
# 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 http://coderunner.org.nz/mod/book/view.php?id=193&chapterid=749. 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:

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.

Richard