CSharp on RPi

From eLinux.org
Revision as of 11:43, 10 March 2013 by JoeStrout (talk | contribs) (Added note about using the mcs compiler, and a couple simple examples)
Jump to: navigation, search

C# can be used, in both compiled and interactive mode, on the Raspberry Pi via Mono.

Installation

To use C#, you must first install the mono-complete package. Under Debian:

sudo apt-get install mono-complete

Under Arch:

sudo pacman -S mono-complete

Usage

To use the interactive C# environment [1], simply type "csharp" at a command prompt. Enter some C# code, and it will be executed or evaluated immediately. Press Ctrl+D (or enter "quit;") to exit.

To compile, use the "mcs" (Mono C Sharp) command [2], specifying the name of your source file. This produces a new file with a ".exe" extension; run this executable with the "mono" command. For example:

mcs HelloWorld.cs mono HelloWorld.exe

Examples

Hello World (Interactive)

The following shows how to launch the C# interactive environment and get it to print "Hello world!"

$ csharp
Mono C# Shell, type "help;" for help

Enter statements below.
csharp> print("Hello world!");
Hello world!
csharp>

Hello World (Compiled)

Put the follow code in a text file called "HelloWorld.cs" (using your favorite text editor; "nano" [3] comes standard). Compile with "mcs HelloWorld.cs" and run with "mono HelloWorld.exe".

using System;

public class HelloWorld {
	public static void Main() {
		Console.WriteLine("Hello world!");
	}
}

Serial Port (Interactive)

This example shows creating the serial port by name (the standard name for the UART on the expansion header is /dev/ttyAMA0), checking its status, opening it, and finally writing some data.

csharp> using System.IO.Ports;
csharp> SerialPort sp = new SerialPort("/dev/ttyAMA0", 9600);
csharp> sp.IsOpen;
false
csharp> sp.Open();
csharp> sp.IsOpen; 
true
csharp> sp.WriteLine("Hello world!");