Posts Tagged ‘Mac’

Creating a sample code snippet runner

May 10, 2010 Leave a comment

This may seem like a strange post but I thought I would share with you how I create code samples and run them. I create classes with the concepts I want to learn and implement IRunnable and my framework lists them in a menu and then you can run the classes. I really quite like this.

Heres the code. Nothing special, I just hope it helps you organise you code when your learning concepts.

Just a note these samples where all developed on Mac OS X Snow Leopard using the latest mono and mondevelop bits.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

namespace CSharpInDepth

	public interface IRunnable{
		void RunExamples();

	public class InvalidSelectionException : Exception{

	public class MenuGenerator{
		private string typeNameToExecute;
		private IEnumerable<string> cachedTypes;
		private RunnerableTypeNameGenerator generator;
		public MenuGenerator ()
			generator = new RunnerableTypeNameGenerator();
			cachedTypes = new List<string>();
		public void GenerateMenu()
			cachedTypes = generator.GetTypes ();
			Console.WriteLine("Enter the number of the type you want to run.");
			if (cachedTypes != null && cachedTypes.Any ()) {
				int counter = 0;
				foreach (string type in cachedTypes){
					Console.WriteLine("{0}. {1}",++counter,type);
		public void AcceptSelection(int selection){
			if(selection < 0)
				throw new InvalidSelectionException();
			typeNameToExecute = cachedTypes.ElementAt(selection - 1); 
		public void Execute(){
			var instance = Activator.CreateInstance(Assembly.GetExecutingAssembly().GetName().FullName, typeNameToExecute);
			var runnerableType = (IRunnable)(instance.Unwrap());
	public class RunnerableTypeNameGenerator{
		public IEnumerable<string> GetTypes(){
			return Assembly.GetExecutingAssembly()
				    .Where(x => x.GetInterfaces().Any(y => y.Name.Equals("IRunnable")))
				    .Select(x => x.FullName);

	class MainClass
		public static void Main (string[] args)
			MenuGenerator generator = new MenuGenerator();
			int selection = Convert.ToInt32(Console.ReadLine());
			Console.WriteLine("You selection was: " + selection);