Using C# on Patas

C# is a powerful general-purpose programming language originally developed by Microsoft. After its approval as a standard by ECMA, it has been independently re-engineered as an open-source implementation which is available on many platforms, including Linux. It is installed and available for use on patas.

Because the mono implementation is extremely compatible, Console-oriented C# programs developed on Windows machines (i.e. with Visual Studio) will typically run on mono without changing the source code. (It is beyond the scope of this document to discuss the compatibility of graphical programs.)

C# programs operate in a fully sandboxed runtime environment which provides garbage-collection. As in Java, Python, and other high-level general-purpose languages, disposal of unused memory objects is tracked and managed by the system, relieving an enormous burden from the application programmer.

1. Sample Program
using System;
 using System.Text;
 
 static class MainClass
 {
 	static void Main(String[] args)
 	{
 		Console.WriteLine("hello world");
 	}
 }
 

To compile on patas:

gmcs hello.cs
 mono hello.exe
 

The reason that this is a two-step process hints at the power of C# over interpreted languages; the first step "compiles" your source file into an intermediate byte-code called MSIL which is later processed by a runtime environment, called the Common Language Runtime, or CLR. This type of virtual instruction set is nothing new in computer science. But an innovation that Microsoft's CLR introduced was that this MSIL code is translated, on an as-needed basis, into actual native machine instructions for the target system. And it's retained in this optimal form as the program runs. This is called Just-in-time, or JIT compilation, and it means that your C# program runs with the performance of true native compilation.

2. Documentation

Microsoft's detailed commercial-quality documentation on C# is available freely on the web. Of primary interest will be the extensive CLR (".NET Framework") class libraries, which provide a wide array of system services and data structures. The mono project also offers a set of documentation.

mono - Documentation Library
MSDN - C# Language Reference
MSDN - .NET Framework Class Library

3. String Manipulation
using System;
 using System.Text;
 
 static class MainClass
 {
 	static void Main(String[] args)
 	{
 		String s = "1.\tThis is a string.";
 		String[] string_arr = s.Split('\t');
 
 		Char[] trim_chars = ".:;,".ToCharArray();
 		String ns = string_arr[0].Trim(trim_chars);
 		int i = Convert.ToInt32(ns);
 
 		Console.WriteLine(i);
 
 		foreach (String s2 in string_arr[1].Split())
 			Console.WriteLine(s2.Replace('s','z'));
 	}
 }
 
4. Reading and Writing Files
using System;
 using System.IO;
 using System.Linq;
 using System.Text;
 
 static class MainClass
 {
 	static void Main(String[] args)
 	{
 		String my_filename = "the_file.txt";
 
 		String data = "Four score and seven years ago.";
 
 		// Write some data to the file
 		int i = 0;
 		using (FileStream fs = new FileStream(my_filename, FileMode.Create, FileAccess.Write, FileShare.None))
 		{
 			using (StreamWriter sr = new StreamWriter(fs, Encoding.GetEncoding(28591)))	// Latin-1
 			{
 				foreach (String s in data.Split())
 					sr.WriteLine((++i).ToString() + ". " + new String(s.ToCharArray().Reverse().ToArray()));
 			}
 		}
 
 		// Read data from the file
 		using (FileStream fs = File.Open(my_filename, FileMode.Open, FileAccess.Read, FileShare.Read))
 		{
 			using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding(28591)))
 			{
 				String s;
 				while (null != (s = sr.ReadLine()))
 					Console.WriteLine(s);
 			}
 		}
 	}
 }
 
5. Hash Table of User-defined Objects
using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 
 public class MyObject
 {
 	public Double d_x;
 	public Double d_y;
 	public Double d_z;
 
 	// constructor
 	public MyObject(Double x_arg, Double y_arg, Double z_arg)
 	{
 		d_x = x_arg; d_y = y_arg; d_z = z_arg;
 	}
 };
 
 static class MainClass
 {
 	static void Main(String[] args)
 	{
 		Dictionary<String, MyObject> ht = new Dictionary<String, MyObject>();
 
 		ht.Add("object 1", new MyObject(3.0, 2.1, Math.PI));
 		ht.Add("object 2", new MyObject(Math.Sqrt(2.0), Math.Log(6.0,10.0), 3.2));
 		ht.Add("3rd object", new MyObject(2.1, 9.9, Double.NaN));
 
 		Console.WriteLine(ht["object 2"].d_x);
 	}
 }
 
6. LINQ Operations

One of the exciting things about mono is that it includes support for one of the latest developments in Microsoft's C# 3.5, namely Language-Integrated Query (LINQ), and its supporting technologies (extension methods and lambda expressions). LINQ allows sophisticated and concise retrieval and manipulation operations to be executed on data collections via native C# language expressions. Categories of operations include aggregation, quantification, conversion, concatenation, retrieval, set (union, intersection, etc.), generation, grouping, join, ordering, projection, partitioning, and restriction (filtering).

LINQ is an expansive topic in its own right. The following simple example gives a glimpse of what is possible.

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 
 static class MainClass
 {
 	static void Main(string[] args)
 	{
 		String[] items = { "cat", "pear", "apple", "cat", "banana", "pear", "pear", "apple" };
 
 		KeyValuePair[] tallies = items.GroupBy(k => k, e => 1)
 				.Select(f => new KeyValuePair<String, int>(f.Key.ToUpper(), f.Sum()))
 				.OrderBy(g => g.Key)
 				.ToArray();
 
 		foreach (KeyValuePair<String, int> kvp in tallies)
 			Console.WriteLine(kvp.Key + '\t' + kvp.Value);
 	}
 }
 

Result:

APPLE   2
 BANANA  1
 CAT     2
 PEAR    3
 

-- Main.gslayden - 14 Nov 2008

Edit | Attach | Watch | Print version | History: r14 | r4 < r3 < r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions...
Topic revision: r1 - 2008-11-14 - gslayden
 
  • Edit
  • Attach
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2026 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback