Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
csharp
System.Console.WriteLine("Hello World!")

Define a string containing special characters

Define the literal string "\#{'}${"}/"
csharp
string verbatim = @"\#{'}${""""}/";
string cStyle = "\\#{'}${\"\"}/";

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
csharp
string output = "This\nIs\nA\nMultiline\nString";
string output = @"This
Is
A
Multiline
String";

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
csharp
int a = 3;
int b = 4;
Console.WriteLine("{0}+{1}={2}", a,b,a+b);

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
csharp
var str = "reverse me";
Console.WriteLine(new String(str.Reverse().ToArray()));

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
csharp
var str = "This is a end, my only friend!";
str = String.Join(" ", str.Split().Reverse().ToArray());
Console.WriteLine(str);

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
csharp
using System;
using System.Text;
using System.Linq; // used for Array.ToList() extension

public class TextWrapper {

/// <summary>
/// Wrap the given text to a given width.
/// </summary>
/// <param name="text">The text to be wrapped</param>
/// <param name="width">The maximum width of each line</param>
/// <param name="prefix">Begin each line with this prefix</param>
/// <returns>The wrapped text</returns>
public string Wrap(string text, int width, string prefix) {

var words = text.Split(' ').ToList();
var result = new StringBuilder(prefix);

width = width - prefix.Length;
prefix = "\n" + prefix;

int lineSize = 0;
foreach (var word in words) {
int wordLen = word.Length;

// Do we need to start a new line?
if ((lineSize + wordLen) > width) {
result.Remove(result.Length - 1, 1); // remove trailing space
lineSize = 0;
result.Append( prefix );
}

result.Append(word).Append(' ');
lineSize += wordLen + 1;
}

return result.ToString();
}

public static void Main() {
var prefix = "> ";
var sentence = "The quick brown fox jumps over the lazy dog. ";

var text = "";
for (int i = 0; i < 10; i++)
text += sentence;

// The description said lines of length 78, but
// the example was 72...
Console.WriteLine(new TextWrapper().Wrap(text, 72, prefix));
}
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
csharp
string str = " hello ";
str = str.Trim();
Console.WriteLine(str);

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
csharp
string output = "Space Monkey"

System.Console.WriteLine(output.ToUpper())

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
csharp
string str = "Caps ARE overRated";
str = str.ToLower() ;
Console.WriteLine(str);

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
csharp
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase("man OF stEEL".ToLowerInvariant());

Find the distance between two points

csharp
System.Drawing.Point p = new System.Drawing.Point(13, 14),
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
csharp
string.Format("{0,8:D8}", 42);

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
csharp
using System;

public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12

for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());

r = new Random(12);

for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
csharp
using System;
using System.Text.RegularExpressions;

public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";

Match match = Regex.Match(oneTwoThree, pattern);

// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}

class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
csharp
using System.Text.RegularExpressions;

class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}

Define an empty list

Assign the variable "list" to a list with no elements
csharp
var list = new List<object>();

Define a static list

Define the list [One, Two, Three, Four, Five]
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
csharp
using System.Collections.Generic;
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
csharp
using System.Collections.Generic;
using System.Linq;

public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
csharp
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };

// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
csharp
List<String> values = new List<string> {"andrew", "bob", "chris", "bob"};

var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
csharp
// Make sure you import the System.Linq namespace.
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
csharp
using System.Collections.Generic;
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}

Remove the last element of a list

csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
csharp
String[] first = { "Bruce", "Tommy Lee", "Bruce" };
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
csharp
using System;
using System.Collections.Generic;
using System.Linq;

namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};

// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}

// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}

// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}

// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52

Console.ReadLine();
}
}
}

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
csharp
using System.Collections.Generic;
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
csharp
using System;
using System.Collections.Generic;
using System.Linq;

// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };

// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}

}

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
csharp
using System.Collections.Generic;
using System.Linq;

// This is a "functional" C# approach

// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;

// Increment the count
map[obj]++;

// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}

public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);

// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
csharp
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
csharp
int age = 41;

if (age > 42)

System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");


Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

csharp
if (age > 84) Console.WriteLine("You are really ancient");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
Console.WriteLine("You are {0}", ((age > 84) ? "really ancient" : (age > 30) ? "middle-aged" : "young"));

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
csharp
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
csharp
int x = 1;

while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
csharp
System.Random die = new System.Random();
int roll;

do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
csharp
string text = "Hello";

for (int i = 0; i < 5; i++)
{
Console.Write(text);
}

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}

Console.WriteLine("Liftoff!");

Read the contents of a file into a string

csharp
string contents = System.IO.File.ReadAllText("filename.txt");

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
csharp
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}

Write a string to a file

csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");

Append to a file

csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");

Process each file in a directory

csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
csharp
DateTime parsedDate = DateTime.Parse("2008-05-06 13:29");
// Ideally, you would catch the potential FormatException or use DateTime.TryParse in production code.

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
csharp
DateTime date = DateTime.Today.AddDays(8);

Console.WriteLine("Day of month: " + date.Day);
Console.WriteLine("Day of year: " + date.DayOfYear);
Console.WriteLine("Month name: " + date.ToString("MMMM"));
Console.WriteLine("Day name: " + date.ToString("dddd"));

// The two ToString calls will use the current locale.
// To get localised month and day names, see http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
csharp
using System.Globalization;

DateTime newYearsDay = new DateTime(2009, 1, 1);
CultureInfo[] locales = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE"),
CultureInfo.CreateSpecificCulture("it-IT"),
CultureInfo.CreateSpecificCulture("nl-NL")
};

foreach (CultureInfo locale in locales)
{
Console.WriteLine(newYearsDay.ToString("D", locale));
}

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
csharp
// Creating a variable first:
DateTime now = DateTime.Now;
Console.WriteLine(now);

// Without creating a variable:
Console.WriteLine(DateTime.Now);
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
csharp
using System;

class Greeter
{
private string name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",name);
}

public Greeter(string name){
this.name = name;
}
}

class Test
{
static void Main()
{
new Greeter("Dante").Greet();
}
}

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
csharp
class Greeter
{
public string Name {get;set;}

public void Greet(){
Console.WriteLine("Hello, {0}",Name);
}

public Greeter(string name){
this.Name = name;
}

// Driver
public static void Main()
{
var g = new Greeter("Dante");

g.Name = "Tommy";
g.Greet();
Console.Write("I have just greated {0}", g.Name);
}
}

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
csharp
// While abstract classes do exist in C#, it is most common to use
// an interface in this type of situation.
// It is a common idiom to prefix interface names with an I
public interface IShape {
string Name { get; }
double Area { get; }
void Print();
}

public class Circle : IShape {

private double Radius { get; set; }
public Circle(double radius) {
Name = "Circle";
Radius = radius;
}

public string Name { get; private set; }
public double Area {
get {
return Math.PI * Radius * Radius;
}
}
public double Circumference {
get {
return Math.PI * (Radius + Radius);
}
}

public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Circumference: {2}\n Radius: {3}",
this.Name,
this.Area,
this.Circumference,
this.Radius
);
}
}

public class Rectangle : IShape {

private double Length { get; set; }
private double Breadth { get; set; }
public Rectangle(double length, double breadth) {
Name = "Rectangle";
Length = length;
Breadth = breadth;
}

public string Name { get; private set; }
public double Area {
get {
return Length * Breadth;
}
}
public double Perimeter {
get {
return (Length * 2) + (Breadth * 2 );
}
}

public void Print() {
Console.WriteLine( " Name: {0}\n Area: {1}\n Perimeter: {2}\n Length: {3}\n Breadth: {4}",
this.Name,
this.Area,
this.Perimeter,
this.Length,
this.Breadth
);
}
}

// Driver
public class InheritanceHeirarchy {
public static void _Main() {
var c = new Circle(2.1);
c.Print();

Console.WriteLine();

var r = new Rectangle(2.2, 3.3);
r.Print();
}
}
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
csharp
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");

string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

double sum=0;

foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
csharp
string cvs ="bread,3,2.50\nmilk,2,3.50";
IList<string> rows = cvs.Split('\n');

System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}