My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.
C#
The most popular language for the .NET platform, quickly passing Java in innovation.
 
C# CODE EXAMPLE created on Tuesday, December 16, 2008 permalink
Simple LINQ to array
Shows how get all names out of an arraylist which end with "n".
ArrayList memberNames = new ArrayList() { "Jim", "John", "George", "Ann"};
memberNames.Add("Alice");

IEnumerable<string> names = memberNames.OfType<string>().Where(x => x.EndsWith("n"));

foreach (string name in names)
{
    Console.WriteLine(name);
}
 
C# CODE EXAMPLE created on Friday, February 06, 2009 permalink
Simple example showing extension methods
Extension methods came along in C# 3.0 and enable you to extend system classes, something that I thought was cool about Ruby when I learned about it. Now you can do it in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TestExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {

            string customerEmailAddress = "test@test.com";
            if (customerEmailAddress.IsValidEmailAddress())
            {
                Console.WriteLine(customerEmailAddress + " is valid.");
            }
            else
            {
                Console.WriteLine(customerEmailAddress + "is NOT valid.");
            }

        }
    }

    public static class Extensions
    {
        public static bool
            IsValidEmailAddress(this string s)
        {
            Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
            return regex.IsMatch(s);
        }
    }

}
 
C# CODE EXAMPLE created on Friday, February 06, 2009 permalink
Simple example of using an anonymous method in C#
Anonymous methods have been around since .NET 2.0. They allow you to program in C# the way you do in Javascript: creating an unnamed function on the fly. In this example, the "anonymous method" is everything that is here: Array.FindAll(integers, anonymousMethodGoesHere). It saves you time since otherwise you named method such as "getEvenNumber" but would only use it once. Anonymous methods make things more compact.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestAnonymousMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            int[] evenIntegers = Array.FindAll(integers,
                                         delegate(int integer)
                                         {
                                             return (integer % 2 == 0);
                                         });

            //show
            foreach (int integer in integers) Console.WriteLine(integer);
            foreach (int integer in evenIntegers) Console.WriteLine(integer);

        }
    }
}

Another common example is when handling events as in:
     listBox     = new ListBox(...);
     textBox     = new TextBox(...);
     addButton = new Button(...);
     addButton.Click += delegate
     {
        listBox.Items.Add(textBox.Text);
     };
 
C# CODE EXAMPLE created on Friday, February 20, 2009 permalink
Regular Expression that strips characters
This regular expression strips non letter/number characters from a string. I've needed this often, didn't know it could be solved with such a simple regular expression. Great for turning titles into file names for instance.
        private string ProtectString(string input)
        {
            return Regex.Replace(input, @"[^a-zA-Z0-9]", string.Empty);
        }
 
C# CODE EXAMPLE created on Saturday, February 21, 2009 permalink
How to store and lookup objects in a dictionary in C#
After years of PHP I had to relearn how to pack objects in an array and then look them up in C#. Here is a dictionary collection. Note that when you pull a Button out and assign its properties new values, the original object's properties in your dictionary also change since both variables are pointing to the same point on the heap.
            Dictionary<string, Button> _userControls = new Dictionary<string, Button>();

            Button button1 = new Button();
            button1.Content = "This is button 1";
            _userControls.Add("one", button1);

            Button button2 = new Button();
            button2.Content = "This is button 2";
            _userControls.Add("two", button2);

            Button button3 = new Button();
            button3.Content = "This is button 3";
            _userControls.Add("three", button3);

            Button newButton = (Button)_userControls["two"];
            TheMessage.Text = newButton.Content.ToString(); // "This is button 2"

            newButton.Content = "This is the new button changed.";
            TheMessage.Text = newButton.Content.ToString(); // "This is the new button changed."
            TheMessage.Text = button2.Content.ToString(); // *** "This is the new button changed."
 
C# CODE EXAMPLE created on Friday, March 06, 2009 permalink
Example of generic method for inversion of control pattern
I was reading Tame Your Software Dependencies for More Flexible Apps by James Kovac and he used this code this.authorizationServicee = ServiceLocator.Find<IAuthorizationService>(); which had generic method syntax which was not immediately clear to me so I build the following environment code to in which it would work to better understand it.
using System;

namespace TestGenericMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            Application application = new Application();
        }
    }

    class Application
    {
        private AuthorizationService authorizationService;

        public Application()
        {
            this.authorizationService = ServiceLocator.Find<IAuthorizationService>();
            Console.WriteLine(this.authorizationService.GetAuthorization(21));
            Console.ReadLine();
        }
    }

    interface IAuthorizationService
    {
        string GetAuthorization(int id);
    }

    class ServiceLocator
    {
        public static AuthorizationService Find<T>()
        {
            AuthorizationService authorizationService = new AuthorizationService();
            authorizationService.TypeBeingAuthorized = typeof(T).FullName;
            return authorizationService;
        }
    }

    class AuthorizationService : IAuthorizationService
    {
        public string TypeBeingAuthorized { get; set; }

        public string GetAuthorization(int id)
        {
            return String.Format("authorization of {0} succeeded", this.TypeBeingAuthorized);
        }
    }

}
 
C# CODE EXAMPLE created on Friday, March 06, 2009 permalink
Simple example of custom attributes in C#
Custom attributes allow you to add metadata to your programs, decorate your code with declarative information. This example and screenshot show how easy it is to create custom attributes and the helpful, typed intellisense that you get when writing custom attributes.
using System.Windows;

namespace TestAttributes
{
    [Author("Jim", version=1.1, team="development")]
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }

    [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
    public class Author : System.Attribute
    {
        private string name;
        public double version;
        public string team;

        public Author(string name)
        {
            this.name = name;
            version = 1.0;
            team = "base";
        }
    }
}
 
C# CODE EXAMPLE created on Monday, March 16, 2009 permalink
Simple example of swappable rules engine using lambda syntax
If you thought reflection was only good for creating intellisense of IDE tools, etc., here is an example of using reflection for "runtime swapping" of search methods. The idea is that you might have customers who can access various search logic basic on their (1) access/payment level, (2) available hardware, etc. Just as we use available methods in the class, you could use available .dlls in a directory.
using System;
using System.Collections.Generic;

namespace TestLambda2
{
    class Program
    {
        static void Main(string[] args)
        {
            string searchRulesMethodName = "SearchRules1";
            Predicate<string> predicate = (Predicate<string>) Delegate.CreateDelegate(typeof(Predicate<string>),
                typeof(Program).GetMethod(searchRulesMethodName));
            var results = GetSearchResults(predicate);

            foreach (string entry in results)
            {
                Console.WriteLine(entry);
            }
            Console.ReadLine();
        }

        //only returns some entries
        public static bool SearchRules1(string entry)
        {
            if (entry == "one" || entry == "two") return true;
            return false;
        }

        //returns all entries
        public static bool SearchRules2(string entry)
        {
            return true;
        }

        public static List<string> GetSearchResults(Predicate<string> p)
        {
            string[] allEntries = { "one", "two", "three", "four", "five", "six", "seven" };
            List<string> results = new List<string>();
            foreach (string entry in allEntries)
            {
                if (p.Invoke(entry))
                {
                    results.Add(entry);
                }
            }
            return results;
        }
    }
}
 
C# CODE EXAMPLE created on Monday, March 16, 2009 permalink
How to get useful information about the currently assembly
Having your application be aware of itself with reflection is quite powerful, e.g. being able to know when new .dlls are added, reacting to its internal classes and methods that build it up. This code gets you started peeking into the assembly itself.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace DynamicAssembly2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Assembly.GetExecutingAssembly().FullName);

            List<Type> types = Assembly.GetExecutingAssembly().GetTypes().ToList<Type>();
            foreach (Type type in types)
            {
                Console.WriteLine("--");
                Console.WriteLine("type.FullName = {0}", type.FullName);
                Console.WriteLine("type.Name = {0}", type.Name);
                Console.WriteLine("type.BaseType = {0}", type.BaseType);
                Console.WriteLine("type.Module = {0}", type.Module);
                Console.WriteLine("type.Namespace = {0}", type.Namespace);
                Console.WriteLine("type.GUID = {0}", type.GUID);
            }
            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Thursday, March 19, 2009 permalink
Example of how to use explicit interface implementation in C#
Ran across this example today when I asked a question about interface implementation on stackoverflow, turns out that you can have two identically named methods in a C# class, one that executes when the object is an instance of the class and one that executes when the object is an instance of the interface. Not sure when you would want/need to use this (and it seems a bit counter-intuitive to what interfaces are supposed to do since you can have a class implement an interface but an instance of that class does not implement that interface), in any case, good to know for when you are doing Composite Application Guidance since this pattern is used frequently in that code.
using System;

namespace TestInterface44
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger logger1 = new Logger();
            logger1.LogAction();

            ILogger logger2 = new Logger();
            logger2.LogAction();

            SimpleLogger logger3 = new SimpleLogger();
            //logger3.LogAction(); gets "method not implemented" error even though SimpleLogger "implements" ILogger
            ((ILogger)logger3).LogAction();

            Console.ReadLine();
        }
    }

    interface ILogger
    {
        void LogAction();
    }

    class Logger : ILogger
    {
        public void LogAction()
        {
            Console.WriteLine("This is Logger.LogAction() logging from an instantied object.");
        }

        void ILogger.LogAction()
        {
            Console.WriteLine("This is Logger.LogAction() logging from an instantied interface.");
        }
    }

    class SimpleLogger : ILogger
    {
        void ILogger.LogAction()
        {
            Console.WriteLine("This is SimpleLogger.LogAction() logging from an instantied interface.");
        }
    }
}
 
C# CODE EXAMPLE created on Thursday, March 19, 2009 permalink
Simplest example of dependency injection
Dependency injection may seem as if it refers to something very complex, but it actually a very simple concept. In this example, a customer class depends on a having a logger in order to function correctly, it writes text out to "a logger" but it doesn't really care what kind of logger it is using, just as long as this logger satisfies the ILogger interface (i.e. has a WriteToLog method). As long as the customer class has this kind of logger it will happily use it and everything will be fine, its "dependency" (the logger) "gets injected" through its constructor, hence the name "dependency injection". This example shows that you can inject various kinds of loggers which do different things, enabling the class to "alter its behavior without the changing its internals", which is the definition of dependency injection. Further, when you use an Inversion of Control container such as Unity, when you get instantiate a customer object with the container as in Customer customer = container.Resolve<Customer>, Unity will automatically inject customer with all the dependencies it needs.
using System;
namespace TestUnityInjection23
{
    public class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer(new BasicLogger());
            Customer customer2 = new Customer(new AdvancedLogger());

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public Customer(ILogger logger)
        {
            logger.WriteToLog("creating the customer");
        }
    }

    public interface ILogger
    {
        void WriteToLog(string text);
    }

    public class BasicLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine(text);
        }
    }

    public class AdvancedLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine("*** {0} ***", text);
        }
    }
}
 
C# CODE EXAMPLE created on Thursday, March 19, 2009 permalink
Example of a generics method signature
I build this example to learn how I could use Generics in my custom methods and classes. Generics is quite powerful for being able to require method parameters to be checked at compile time, very useful, especially if you are going to be returning an object of the type passed as in my InstantiateType example below. This code is also being discussed here at StackOverflow.
using System;

namespace TestGeneric33
{
    class Program
    {
        static void Main(string[] args)
        {
            Container container = new Container();
            Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
            Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
            Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
            Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
            Console.ReadLine();
        }
    }

    public class Container
    {
        public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
        {
            T obj = new T();
            obj.FirstName = firstName;
            obj.LastName = lastName;
            return obj;
        }
    }

    public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get; set; }

    }

    public class PersonDisplayer
    {
        private IPerson _person;

        public PersonDisplayer(IPerson person)
        {
            _person = person;
        }

        public string SimpleDisplay()
        {
            return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
        }

        public static string SimpleDisplay(IPerson person)
        {
            PersonDisplayer personDisplayer = new PersonDisplayer(person);
            return personDisplayer.SimpleDisplay();
        }
    }

    public class Customer : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
    }

    public class Employee : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int EmployeeNumber { get; set; }
    }
}
 
C# CODE EXAMPLE created on Friday, March 20, 2009 permalink
Simple example of C# delegates
This example shows how delegates are types that simply reference a method which has a certain signature (return type and parameters). To show how a task can be accomplished with and without delegates, each way accesses the same methods which actually do the work.
using System;

namespace TestDelegates
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Without delegates:");
            Mathematician mathematician = new Mathematician();

            Console.WriteLine("With delegates:");
            DelegateMathematician delegateMathematician = new DelegateMathematician();
            Console.ReadLine();
        }
    }

    class Mathematician
    {
        public Mathematician()
        {
            Console.WriteLine("10 plus 20 = {0}", LogicEquations.AddNumbers(10, 20));
            Console.WriteLine("10 times 20 = {0}", LogicEquations.MultiplyNumbers(10, 20));
            Console.WriteLine("10 minus 20 = {0}", LogicEquations.SubtractNumbers(10, 20));
            Console.WriteLine();
        }
    }

    class DelegateMathematician
    {
        public delegate int Equation(int a, int b);

        public DelegateMathematician()
        {
            Equation adder = new Equation(LogicEquations.AddNumbers);
            Equation multiplier = new Equation(LogicEquations.MultiplyNumbers);
            Equation subtracter = new Equation(LogicEquations.SubtractNumbers);
            
            Console.WriteLine("The delegate that adds says about 10 and 20: {0}", adder(10, 20));
            Console.WriteLine("The delegate that multiplies says about 10 and 20: {0}", multiplier(10, 20));
            Console.WriteLine("The delegate that subtracts says about 10 and 20: {0}", subtracter(10, 20));
            Console.WriteLine();
        }
    }

    public static class LogicEquations
    {
        public static int AddNumbers(int a, int b)
        {
            return a + b;
        }

        public static int MultiplyNumbers(int a, int b)
        {
            return a * b;
        }

        public static int SubtractNumbers(int a, int b)
        {
            return a - b;
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, March 25, 2009 permalink
How to call a property of an object with a variable in C#
This is a little method using reflection that returns the value of a property of an object sent as a variable. I only needed it for string variables but you could easily extend it for integers, etc. or make it generic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace TestLinqFieldIndex
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { ID = 1, FirstName = "Jim", LastName = "Smith" });
            customers.Add(new Customer { ID = 2, FirstName = "Joe", LastName = "Douglas" });
            customers.Add(new Customer { ID = 3, FirstName = "Jane", LastName = "Anders" });

            var customer = (from c in customers
                            where c.ID == 2
                            select c).SingleOrDefault();

            string[] fieldNames = { "FirstName", "LastName" };
            foreach (string fieldName in fieldNames)
            {
                Console.WriteLine("The value of {0} is {1}.", fieldName, customer.GetPropertyValue(fieldName));
            }

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string GetPropertyValue(string fieldName)
        {
            PropertyInfo prop = typeof(Customer).GetProperty(fieldName);
            return prop.GetValue(this, null).ToString();
        }

    }
}
 
C# CODE EXAMPLE created on Friday, April 17, 2009 permalink
How to use the params keyword for more flexible methods
This demonstrates how using the params keyword can make your methods more flexible by allowing you to pass any number of parameters.
using System;

namespace TestParam222
{
    class Program
    {
        static void Main(string[] args)
        {
            //old way
            int[] theIntegers = { 5, 5, 7, 3, 2, 8, 1 };
            Console.WriteLine("The total is {0}.", Tools.AddIntegers(theIntegers));

            //new way
            Console.WriteLine("The total is {0}.", Tools.AddIntegersBetter());
            Console.WriteLine("The total is {0}.", Tools.AddIntegersBetter(2));
            Console.WriteLine("The total is {0}.", Tools.AddIntegersBetter(2, 3, 1));
            Console.WriteLine("The total is {0}.", Tools.AddIntegersBetter(2, 3, 1, 2, 2));

            Console.ReadLine();
        }
    }

    class Tools
    {
        public static int AddIntegers(int[] integers)
        {
            int sum = 0;
            foreach (int i in integers)
            {
                sum += i;
            }
            return sum;
        }

        public static int AddIntegersBetter(params int[] integers)
        {
            int sum = 0;
            foreach (int i in integers)
            {
                sum += i;
            }
            return sum;
        }
    }
}
 
C# CODE EXAMPLE created on Friday, April 17, 2009 permalink
Simple example of LINQ method syntax using lambdas
LINQ can be expressed in two ways: query syntax (like SQL) and method syntax (using lamdbas). Query syntax is easier to read but method syntax can be much more terse. Here is an example of using method syntax with lambdas. Notice below that the lambda syntax has been commented out and the equivalent delegate structures are used to show what the lambda is actually doing.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestLambda23
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer> {
                new Customer {FirstName="Jim", LastName="Smith", Age=27},
                new Customer {FirstName="Hank", LastName="Moore", Age=30},
                new Customer {FirstName="Jay", LastName="Smythe", Age=44},
                new Customer {FirstName="Angie", LastName="Thompson", Age=55},
                new Customer {FirstName="Sarah", LastName="Conners", Age=66}
            };

            //var youngerCustomers = customers.Where(c => c.Age <= 30);
            var youngerCustomers = customers.Where(
                delegate(Customer c) {
                    return c.Age <= 30;
                });

            //var olderCustomers = customers.Where(c => c.Age > 30);
            var olderCustomers = customers.Where(
                delegate(Customer c)
                {
                    return c.Age > 30;
                });

            Console.WriteLine("Younger:");
            foreach (var customer in youngerCustomers)
            {
                Console.WriteLine(customer.Show());
            }

            Console.WriteLine("Older:");
            foreach (var customer in olderCustomers)
            {
                Console.WriteLine(customer.Show());
            }

            Console.WriteLine(string.Format("Average age is {0:0}.", customers.Average(c => c.Age)));

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public string Show()
        {
            return String.Format("{0} {1} ({2})", FirstName, LastName, Age);
        }
    }
}

 
C# CODE EXAMPLE created on Saturday, April 18, 2009 permalink
Simplest example of creating a lambda expression with Func<>
Using Func<> is a way to create a method that you can pass around, the first parameters in Func are the method parameters and the last is the return type.
using System;

namespace TestLambda23432
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int, int> AddThem = (x, y) => x + y;
            Console.WriteLine("The result is: {0}.", AddThem(16, 4));

            Func<string, string> CapitalizeIt = (baseString) => baseString.ToUpper();
            Console.WriteLine("The capitalized string is: {0}.", CapitalizeIt("testing"));

            Func<string, bool> PasswordIsCorrect = p => p == "pass33";
            if (PasswordIsCorrect("pass33"))
            {
                Console.WriteLine("password was correct");
            }
            else
            {
                Console.WriteLine("password was INCORRECT");
            }

            Console.ReadLine();
        }
    }
}

 
C# CODE EXAMPLE created on Saturday, April 18, 2009 permalink
Code example showing the evolution of lambda expressions using C# 1, C# 2, and C# 3
The following method Tools.Filter functions just like .Where<> in LINQ. This shows you some of what is going on behind the scenes in the Where method used often in LINQ. The examples give you a sense of the evolution in C# leading up to Lambda. For more of this, check out Jon Skeet's article on C# closures.
using System;
using System.Collections.Generic;

namespace TestLambda28892
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "Jim", "Joe", "Hank", "Alice" };

            //C# 1 (predicates)
            Predicate<string> predicate = new Predicate<string>(MatchStartWithJ);
            IList<string> namesWithJ = Tools.Filter(names, predicate);
            Tools.Dump(namesWithJ);

            //C# 2 (anonymous methods)
            Predicate<string> predicate2 = delegate(string item)
            {
                return item.StartsWith("J");
            };
            IList<string> namesWithJ2 = Tools.Filter(names, predicate);
            Tools.Dump(namesWithJ2);

            //C# 3 (lambda expressions)
            var filteredNames = Tools.Filter(names, n => n.StartsWith("J"));
            Tools.Dump(filteredNames);

            Console.ReadLine();

        }

        static bool MatchStartWithJ(string item)
        {
            return item.StartsWith("J");
        }
    }

    public static class Tools
    {
        public static IList<T> Filter<T>(IList<T> source, Predicate<T> predicate)
        {
            List<T> ret = new List<T>();
            foreach (T item in source)
            {
                if (predicate(item))
                {
                    ret.Add(item);
                }
            }
            return ret;
        }

        public static void Dump<T>(IList<T> items)
        {
            foreach (var name in items)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine("---");
        }

    }
}
 
C# CODE EXAMPLE created on Saturday, April 18, 2009 permalink
Understanding variable context in closures when using the System.Action delegate
This example from Jon Skeet's article on closures shows an issue that you have to keep in mind when using System.Action: that your closure saves the variable itself and not the value of the variable (as does Java for instance).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLambda8811
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Action> actions = new List<Action>();
            for (int count = 1; count <= 10; count++)
            {
                actions.Add(() => Console.WriteLine(count));
            }
            foreach (Action action in actions)
            {
                action();
            }
            actions.Clear();


            for (int count = 1; count <= 10; count++)
            {
                int copy = count;
                actions.Add(() => Console.WriteLine(copy));
            }

            foreach (Action action in actions)
            {
                action();
            }

            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Saturday, April 18, 2009 permalink
Simplest example of C# delegates
This example shows that a delegate is nothing more than a pointer to a function. They simply specify a specific method to call.
using System;

namespace TestDelegate
{
    class Program
    {
        private delegate void WriteHandler(string message);

        static void Main(string[] args)
        {
            WriteHandler writeIt = new WriteHandler(WriteAndWait);
            writeIt("hello");
        }

        public static void Write(string message)
        {
            Console.WriteLine(message);
        }

        public static void WriteAndWait(string message)
        {
            Console.WriteLine(message);
            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Saturday, April 18, 2009 permalink
Simplest use of the C# System.Action delegate
Need to understand the line "public RelayCommand(Action<object> execute, Predicate<object> canExecute)" so put the following code together that uses Action<string>. You can put any number of parameters into the Action, e.g. Action<int, string, bool> but then each method that it could point to needs to have the same signature. Action is simply a delegate which does not have a return variable. Notice also the use of List.ForEach(...) which cuts the foreach blocks to one line, nice.
using System;
using System.Collections.Generic;

namespace TestDelegate
{
    class Program
    {
        private delegate void WriteHandler(string message);

        static void Main(string[] args)
        {
            List<string> words = new List<string>() { "one", "two", "three", "four", "five" };
            Action<string> theFunction = WriteBasic;

            words.ForEach(word => theFunction(word));
            Console.ReadLine();
        }

        public static void WriteBasic(string message)
        {
            Console.WriteLine(message);
        }

        public static void WriteAdvanced(string message)
        {
            Console.WriteLine("*** {0} ***", message);
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, April 22, 2009 permalink
Code Example which shows that "as" returns null if it cannot cast
I thought the "as" keyword would throw an exception if it could not cast. Turns out that it simply returns null, helped me to understand this code.
using System;

namespace TestAs234
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            Employee employee = new Employee();

            Person.Test(customer);
            Person.Test(employee);
            Console.ReadLine();
        }

    }

    class Person
    {
        public static void Test(object obj)
        {
            Person person = obj as Customer;

            if (person == null)
            {
                Console.WriteLine("person is null");
            }
            else
            {
                Console.WriteLine("person is of type {0}", obj.GetType());
            }
        }
    }

    class Customer : Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Employee : Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

}
 
C# CODE EXAMPLE created on Wednesday, April 22, 2009 permalink
Why not to use public fields on C# classes
I asked a question about using public readonly fields on stackoverflow which pointed me to a good article on properties by Jon Skeet in which he gives an example of how switching from public fields to properties can cause logical changes in your code without even breaking it (bad). The prerequisite is that you are using structs. I remade the code and tested it here.
using System;

namespace TestFieldProperty234
{
    class Program
    {
        static void Main(string[] args)
        {
            TheStructHolder holder = new TheStructHolder();
            holder.Field.SetValue(10);
            holder.Property.SetValue(10);

            Console.WriteLine(holder.Field.Value);
            Console.WriteLine(holder.Property.Value);
            Console.ReadLine();
        }
    }

    struct TheStruct
    {
        public int Value { get; set; }

        public void SetValue(int newValue)
        {
            Value = newValue;
        }
    }

    class TheStructHolder
    {
        public TheStruct Field;
        public TheStruct Property { get; set; }
    }

}
 
C# CODE EXAMPLE created on Wednesday, April 22, 2009 permalink
Example of C#'s null coalescing operator
Ran into the ?? operator in C# and needed to try it out. It is a terse and convenient way to make sure a variable has a value, i.e. if an only if it is null, then it gets the value prescribed.
using System;

namespace DoubleQuestion
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintTheName("Jim");
            PrintTheName("John");
            PrintTheName(null);

            Console.ReadLine();
        }

        static void PrintTheName(string name)
        {
            //string nameToPrint = name ?? String.Empty;
            string nameToPrint = name ?? "(unknown name)";
            Console.WriteLine("the name is {0}", nameToPrint);
        }

    }
}
 
C# CODE EXAMPLE created on Friday, May 15, 2009 permalink
How to convert and filter List<object> to List<string> in C# 3.0
If you have a list of various types of objects here are two ways to convert them to strings, the second way looks for a specific type of object with .OfType.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestOfType
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Allison";
            Customer customer1 = new Customer { FirstName = "Jim", LastName = "Rogers", Age = 22 };
            int age = 34;
            Customer customer2 = new Customer { FirstName = "Joe", LastName = "Smith", Age = 43 };
            List<object> objects = new List<object>();
            objects.Add(name);
            objects.Add(customer1);
            objects.Add(age);
            objects.Add(customer2);

            //show all as string
            List<string> simpleNames = objects.Select(i => i.ToString()).ToList();
            foreach (string simpleName in simpleNames)
            {
                Console.WriteLine("Simple name of object: {0}", simpleName);
            }
            Console.WriteLine();

            //show only customers
            List<Customer> customers = objects.OfType<Customer>().ToList();
            foreach (Customer customer in customers)
            {
                Console.WriteLine("Customer: {0}", customer.ToString());
            }

            Console.ReadLine();
        }
    }

    class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public override string ToString()
        {
            return String.Format("{1}, {0} ({2})", FirstName, LastName, Age);
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, June 10, 2009 permalink
Basic singular/plural model classes using "load code"
This is a C# implementation of how I have created model classes in other languages, basically you have a singular and plural class for each database table/feed/source and you instantiate these with the new keyword and a "load code". As you begin to program, you can define load codes as strings and then later implement a query engine etc. or, you can have special load codes which, e.g. load more or less into objects based on what you need in the context, e.g. you could have a "customerLight" loadCode with only the properties, but also a "customerFull" which also loaded all of the customers collections of associated contacts, reports, orders, contracts, etc.
using System.Collections.Generic;
using System;

namespace TestFactory234
{
    public class Program
    {
        static void Main(string[] args)
        {
            SmartForms smartForms = new SmartForms("all");
            smartForms.Show();

            SmartForm smartForm = new SmartForm("id = 34");
            smartForm.Show();

            Console.ReadLine();
        }
    }

    public class SmartForm
    {
        private string _loadCode;

        public string IdCode { get; set; }
        public string Title { get; set; }

        public SmartForm() { }

        public SmartForm(string loadCode)
        {
            _loadCode = loadCode;
            SmartForms smartForms = new SmartForms(_loadCode);
            if(smartForms.Collection.Count > 0)
            {
                Clone(smartForms.Collection[0] as SmartForm);
            }
        }

        private void Clone(SmartForm smartForm)
        {
            IdCode = smartForm.IdCode;
            Title = smartForm.Title;
        }

        public void Show()
        {
            Console.WriteLine("This SmartForm has idCode={0} and title={1}.", IdCode, Title);
        }


    }

    public class SmartForms
    {
        private string _loadCode;

        public List<SmartForm> _collection = new List<SmartForm>();
        public List<SmartForm> Collection
        {
            get
            {
                return _collection;
            }
        }

        public SmartForms(string loadCode)
        {
            _loadCode = loadCode;
            Load();
        }

        //fills internal collection from data source, based on "load code"
        private void Load()
        {
            switch (_loadCode)
            {
                case "all":
                    SmartForm smartFormA = new SmartForm { IdCode = "customerMain", Title = "Customer Main" };
                    SmartForm smartFormB = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" };
                    SmartForm smartFormC = new SmartForm { IdCode = "customerMain3", Title = "Customer Main3" };
                    _collection.Add(smartFormA);
                    _collection.Add(smartFormB);
                    _collection.Add(smartFormC);
                    break;
                case "id = 34":
                    SmartForm smartForm2 = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" };
                    _collection.Add(smartForm2);
                    break;
                default:
                    break;
            }
        }

        public void Show()
        {
            foreach (SmartForm smartForm in _collection)
            {
                smartForm.Show();
            }
        }

    }
}
 
C# CODE EXAMPLE created on Wednesday, June 10, 2009 permalink
Abstract class pattern for C#
I think about 80% of the usefulness of OOP comes down to having abstract classes which (1) provide certain functionality to their inheriting classes, and (2) require certain functionality of their inheriting classes (the other 20% is mostly interfaces and contructors). This is one of the first code examples that I do for languages that I'm learning. Here it is in C#. It is quite simple but you have to know that you don't need all the "internal", "new", "virtual" keywords and that you DO need the "override" keyword for the method which override abstract methods (different than in PHP).
using System;

namespace TestOverriding234
{
    public class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer { Id = 1, FirstName = "Jim", LastName = "Smith" };
            Contract contract = new Contract { Id = 2, Title = "First Contract", Description = "This is the first contract" };

            customer.ShowSystemFields();
            contract.ShowSystemFields();

            Console.ReadLine();
        }
    }

    public class Customer : Item
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public override void Load()
        {
            throw new NotImplementedException();
        }
    }

    public class Contract : Item
    {
        public string Title { get; set; }
        public string Description { get; set; }

        public override void Load()
        {
            throw new NotImplementedException();
        }
    }

    public abstract class Item
    {
        public int Id { get; set; }

        public void ShowSystemFields()
        {
            Console.WriteLine("This item is a {0} and has Id={1}", this.GetType().Name, this.Id);
        }

        public abstract void Load();

    }
}
 
C# CODE EXAMPLE created on Wednesday, June 10, 2009 permalink
How to extract a piece of a string out of a string with Regex
If you are writing any kind of parser, regular expressions are invaluable. Here is the basic code for recognizing and picking out an integer from the right size of a operation statement.
using System;
using System.Text.RegularExpressions;

namespace TestRegex
{
    class Program
    {
        static void Main(string[] args)
        {
            //string input = "id = 1";
            //string input = "id = 222";
            //string input = "id = 324234";
            //string input = "id = id"; // won't match
            //string input = "id = "; // won't match
            string input = "id = 232";
            Match match = Regex.Match(input, @"id = ([0-9]+)$");
            if (match.Success)
            {
                string key = match.Groups[1].Value;
                Console.WriteLine(key);
            }
            else
            {
                Console.WriteLine("no match");
            }

            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, June 17, 2009 permalink
How to get and set properties of an object dynamically with reflection
These two methods can be used on on object so that you can e.g. parse an XML file that has changes in it, and make changes on an object based on the strings in the XML file.
using System;
using System.Reflection;

namespace TestSetPropertyValue834
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer { Id = 1, FirstName = "Jim", LastName = "Smith" };

            Console.WriteLine(customer.LastName);
            Console.WriteLine(customer.GetPropertyValueAsString("LastName"));
            customer.SetPropertyValueWithString("LastName", "SmithChanged");
            Console.WriteLine(customer.GetPropertyValueAsString("LastName"));
            Console.ReadLine();
        }
    }

    class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public string GetPropertyValueAsString(string propertyName)
        {
            PropertyInfo prop = typeof(Customer).GetProperty(propertyName);
            object value = prop.GetValue(this, null);
            return value.ToString();
        }

        public void SetPropertyValueWithString(string propertyName, string value)
        {
            PropertyInfo prop = typeof(Customer).GetProperty(propertyName);
            prop.SetValue(this, value, null);
        }
    }
}
 
C# CODE EXAMPLE created on Thursday, June 25, 2009 permalink
Four ways to create an XML file
Here are four ways to create the same XML string that I needed for an application: string concatenation, XmlWriter, LINQ-to-XML, in reverse order of preference (plus an example using XML literals which Jim Wooley posted on his site along with some notes on the dangers of string concatenation). These code samples assume an object called DataType which is not included in the code, so the code isn't executable as is, but I just wanted to record the syntax of each way for further reference. Notice the Enumerable.Range(1, 3).Select on the LINQ-to-XML functions as a for loop.
String Concatentation:
    StringBuilder sb = new StringBuilder();
    sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine);

    sb.Append(String.Format("<{0}>{1}", _pluralCamelNotation, Environment.NewLine));
    for (int index = 0; index < 3; index++)
    {
        sb.Append(String.Format("\t<{0}>{1}", _singularCamelNotation, Environment.NewLine));
        foreach (DataType dataType in _allDataTypes)
        {
            sb.Append(String.Format("\t\t<{0}>{2}</{0}>{1}", dataType.CamelCaseNotation, Environment.NewLine, dataType.GetDummyData()));
        }
        sb.Append(String.Format("\t</{0}>{1}", _singularCamelNotation, Environment.NewLine));
    }
    sb.Append(String.Format("</{0}>{1}", _pluralCamelNotation, Environment.NewLine));

XmlWriter:
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.Entitize;
            settings.Indent = true;
            settings.IndentChars = "\t";

            StringBuilder sb = new StringBuilder();
            using (XmlWriter xw = XmlWriter.Create(sb, settings))
            {
                xw.WriteStartDocument();
                xw.WriteStartElement(_pluralCamelNotation);
                for (int i = 0; i < 3; i++)
                {
                    xw.WriteStartElement(_singularCamelNotation);
                    foreach (DataType dataType in _allDataTypes)
                    {
                        xw.WriteElementString(dataType.CamelCaseNotation, dataType.GetDummyData());
                    }
                    xw.WriteEndElement();
                }
                xw.WriteEndElement();
                xw.WriteEndDocument();
                xw.Close();
            }
            return sb.ToString();

XML Literals (VB.NET):

        Dim doc = <?xml version="1.0"?>
                    <<%= _pluralCamelNotation %>>
                        <%= From i In Enumerable.Range(1, 3) _
                            Select <<%= _singluarNotation %>>
                                     <%= From t In _allDataTypes _
                                         Select <<%= t.CamelCaseNotation %>>
                                             <%= t.GetDummyData %></> %>
                                 </> %>
                    </>

LINQ-to-XML:
            XDocument doc = new XDocument(
                new XDeclaration("1.0", null, null),
                new XElement(_pluralCamelNotation,
                    Enumerable.Range(1, 3).Select(
                        i => new XElement(_singularCamelNotation,
                            _allDataTypes.Select(
                                dataType => new XElement(
                                    dataType.CamelCaseNotation,
                                    dataType.GetDummyData())
                            )
                    ))));
            return doc.ToString();
 
C# CODE EXAMPLE created on Tuesday, July 07, 2009 permalink
How to convert a Generic List to an ObservableCollection in one line with a lambda
You can never internalize too many lambda expression code examples, wonderful terseness. This one converts a List to an ObservableCollection in one line.
            List<string> names = new List<string>() { "Jim", "Joe", "Jane" };
            ObservableCollection<string> onames = new ObservableCollection<string>();

            names.ForEach(x => onames.Add(x));
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
How to serialize and deserialize an ObservableCollection
This example shows you how to save an ObservableCollection to an XML file and then read it back in.
XAML:
<Window x:Class="TestXmlSerialize123.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    
    <Window.Resources>
        <DataTemplate x:Key="CustomerListTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text=" "/>
                <TextBlock Text="{Binding LastName}"/>
            </StackPanel>
        </DataTemplate>
        
    </Window.Resources>
    
    <Grid>
        <ItemsControl ItemsSource="{Binding CustomerList}"
                        ItemTemplate="{StaticResource CustomerListTemplate}"/>
    </Grid>
</Window>

Code-Behind:
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using System.IO;

namespace TestXmlSerialize123
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        private ObservableCollection<Customer> _customerList = new ObservableCollection<Customer>();
        public ObservableCollection<Customer> CustomerList
        {
            get
            {
                return _customerList;
            }

            set
            {
                _customerList = value;
                OnPropertyChanged("CustomerList");
            }
        }

        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            bool readFromXmlFile = true;

            if (readFromXmlFile)
            {
                XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
                using (StreamReader rd = new StreamReader("Data/customers.xml"))
                {
                    CustomerList = xs.Deserialize(rd) as ObservableCollection<Customer>;
                }
            }
            else
            {
                CustomerList.Add(new Customer { FirstName = "Jim", LastName = "Jones" });
                CustomerList.Add(new Customer { FirstName = "Joe", LastName = "Adams" });

                XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
                using (StreamWriter wr = new StreamWriter("Data/customers.xml"))
                {
                    xs.Serialize(wr, CustomerList);
                }
            }

        }


        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }
    }
}
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
How to use EventAggregator in Prism (Composite Application Library)
Getting one module to communicate with another in a Prism application is much easier than it seems. This application shows you how. After you get the four classes copied into your ApplicationCore.Helpers module, publishing and consuming events is as easy as shown below.
How to publish an event in one module:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    (Message.Text as object).PublishEvent(PublishEventNames.MessageTextChanged);
}

How to subscribe to that event in another module:
ServicesFactory.EventService.GetEvent<GenericEvent<object>>().Subscribe(s =>
{
    if (s.Topic == PublishEventNames.MessageTextChanged)
    {
        DisplayArea.Text = String.Format("An event happened in a different module and sent this text    : {0}", s.Value.ToString());
    }
});
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
Basic foreground and background threads
This example shows you how to call a method on foreground and background threads. Note that the threads are are executed in a seemingly random order.
using System;
using System.Threading;

namespace TestThreading828
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("before we start");

            int availableThreads = 0;
            int other = 0;
            ThreadPool.GetAvailableThreads(out availableThreads, out other);
            Console.WriteLine("Available threads = {0}", availableThreads);

            ThreadPool.QueueUserWorkItem(DoWork, "thread 1");
            ThreadPool.QueueUserWorkItem(DoWork, "thread 2");
            ThreadPool.QueueUserWorkItem(DoWork, "thread 3");
            DoWork("thread 4");
            DoWork("thread 5");
            ThreadPool.QueueUserWorkItem(DoWork, "thread 6");
            ThreadPool.QueueUserWorkItem(DoWork, "thread 7");
            DoWork("thread 8");
            ThreadPool.QueueUserWorkItem(DoWork, "thread 9");

            Console.WriteLine("before we pause");
            Thread.Sleep(1000);

            Console.WriteLine("Finished.");
            Console.ReadLine();
        }

        static void DoWork(object param)
        {
            string message = (string)param;
            if (Thread.CurrentThread.IsBackground)
            {
                Console.WriteLine("BACKGROUND thread: {0}", message);
            }
            else
            {
                Console.WriteLine("foreground thread: {0}", message);
            }
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
How to abort a thread
This example shows how to abort a thread. Notice though that "DoWork has ended" is never shown since we abort it while it is sleep, so it just goes through its catch and finally but does nothing else. If you pause the main thread long enough for the DoWork to finish, then you will see the "DoWork has ended" message. But make sure you know why aborting a thread is a bad idea (may leave application in unstable state, etc.).
using System;
using System.Threading;

namespace TestThreading838
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("MAIN THREAD started.");

            Thread DoWorkThread = new Thread(new ThreadStart(DoWork));

            DoWorkThread.Start();
            Thread.Sleep(1000); //change to 6000 to let DoWork finish and print "DoWork has ended."

            DoWorkThread.Abort();

            Console.WriteLine("MAIN THREAD ending...");
            Thread.Sleep(6000);
            Console.WriteLine("MAIN THREAD ended.");

            Console.ReadLine();
        }

        public static void DoWork()
        {
            Console.WriteLine("DoWork is running.");
            try
            {
                Thread.Sleep(5000);
            }
            catch (ThreadAbortException ex)
            {
                Console.WriteLine("DoWork was aborted.");
            }
            finally
            {
                Console.WriteLine("DoWork cleaning up after being aborted.");
            }
            Console.WriteLine("DoWork has ended."); //never shown
        }

    }
}
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
How to send a parameter to a method in a thread
This example shows how to set up a method in a thread so that you can pass a parameter to it and have it optionally call a delegate method when it is finished.
using System;
using System.Threading;

namespace TestThreading8338
{
    class Program
    {
        static void Main(string[] args)
        {
            AddStars addStars = new AddStars("this is a test", new ResultDelegate(ResultCallBack));
            //AddStars addStars = new AddStars("this is a test", null);

            Thread t = new Thread(new ThreadStart(addStars.ThreadProc));
            t.Start();
            Console.WriteLine("main thread runs");
            t.Join();
            Console.WriteLine("Thread completed.");
            Console.ReadLine();
        }

        public static void ResultCallBack(string retValue)
        {
            Console.WriteLine("Returned value: {0}", retValue);
        }
    }

    public class AddStars
    {
        private string message;
        private ResultDelegate callback;

        public AddStars(string message, ResultDelegate callback)
        {
            this.message = message;
            this.callback = callback;
        }

        public void ThreadProc()
        {
            Console.WriteLine("ThreadProc is processing: " + message);
            if(callback != null)
                callback(String.Format("* {0} *", message));
        }
    }

    public delegate void ResultDelegate(string value);
}
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
How to lock threads so that they don't overwrite variables
If you take out the "lock" statements in the following code, you will get some surprising results since the object in the last thread overwrites the values of the objects in the first to threads since they aren't finished processing yet. Therefore it is important to always remember that within a thread you have to lock any access to internal variables (or any shared resources) since although obvious in this example, not doing so could lead to some very hard to find bugs. Note there is also the ReaderWriterLock and Interlocked classes.
using System;
using System.Threading;

namespace TestThreading0028
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer("Jim", "Smith", 35);

            Thread t1 = new Thread(new ThreadStart(customer.ShowSimple));
            Thread t2 = new Thread(new ThreadStart(customer.ShowFancy));
            Thread t3 = new Thread(new ThreadStart(customer.ShowFull));

            t1.Start();
            t2.Start();
            t3.Start();

            Console.ReadLine();
        }
    }

    public class Customer
    {
        private string firstName;
        private string lastName;
        private int age;
        private string result;

        public Customer(string firstName, string lastName, int age)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }

        public void ShowSimple()
        {
            lock (this)
            {
                result = String.Format("{0} {1}", firstName, lastName);
                Thread.Sleep(1000);
                Console.WriteLine(result);
            }
        }

        public void ShowFancy()
        {
            lock (this)
            {
                result = String.Format("*** {1}, {0} ****", firstName, lastName);
                Thread.Sleep(1000);
                Console.WriteLine(result);
            }
        }

        public void ShowFull()
        {
            lock (this)
            {
                result = String.Format("{0} {1} ({2})", firstName, lastName, age);
                Thread.Sleep(1000);
                Console.WriteLine(result);
            }
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, July 29, 2009 permalink
How to wait for multiple threads to finish
If you just need to wait for one thread to finish, you can call its Join() method. This example shows how you can process multiple threads in a more organized manner by adding them to a queue and then having them be processed one after another.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestThreadingWaitMultiple
{
    class Program
    {
        static AutoResetEvent[] waitHandles = new AutoResetEvent[]
        {
            new AutoResetEvent(false),
            new AutoResetEvent(false),
            new AutoResetEvent(false)
        };

        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessCustomer), new ThreadInfo(1000, waitHandles[0]));
            ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessCustomer), new ThreadInfo(750, waitHandles[1]));
            ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessCustomer), new ThreadInfo(500, waitHandles[2]));

            WaitHandle.WaitAll(waitHandles);

            Console.WriteLine("Main thread is complete.");
            Console.ReadLine();

        }

        static void ProcessCustomer(object state)
        {
            ThreadInfo ti = (ThreadInfo)state;
            Thread.Sleep(ti.milliseconds);
            Console.WriteLine("Waited for {0} milliseconds", ti.milliseconds);
            ti.autoResetEvent.Set();
        }
    }

    class ThreadInfo
    {
        public AutoResetEvent autoResetEvent;
        public int milliseconds;

        public ThreadInfo(int milliseconds, AutoResetEvent autoResetEvent)
        {
            this.autoResetEvent = autoResetEvent;
            this.milliseconds = milliseconds;
        }
    }
}
 
C# CODE EXAMPLE created on Thursday, September 10, 2009 permalink
How to use AsyncCallback to know when method is finished on another thread
This examples shows how to call a method and then have a another method get called when that method is finished.
using System;
using System.Threading;

namespace TestAsync
{
    public delegate int BinaryOperation(int x, int y);

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main invoked on thread {0}.", Thread.CurrentThread.GetHashCode());

            BinaryOperation b = new BinaryOperation(MultiplyIt);
            IAsyncResult result = b.BeginInvoke(3, 5, new AsyncCallback(MultiplyItComplete), null);

            Console.WriteLine("Continuing after starting MultiplyIt...");

            Console.ReadLine();
        }

        static void MultiplyItComplete(IAsyncResult result)
        {
            Console.WriteLine("MultiplyItComplete invoked on thread {0}", Thread.CurrentThread.GetHashCode());
            Console.WriteLine("Multiplying is finished.");
        }

        static int MultiplyIt(int x, int y)
        {
            Console.WriteLine("MultiplyIt invoked on thread {0}.", Thread.CurrentThread.GetHashCode());
            Thread.Sleep(2000);
            return x * y;
        }
    }
}
 
C# CODE EXAMPLE created on Monday, October 12, 2009 permalink
How to alias a type with the using statement
Progammers coming from C or C++ might be looking for the typedef statement in C#. You can use using which does about the same thing. I use it now and then to avoid namespace classes or just to keep code cleaner.
XAML:
<Window x:Class="TestUsing9283.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <TextBlock x:Name="Message"/>
    </Grid>
</Window>

Code-Behind:
using System.Windows;
using System.Windows.Media;
using TheBrush = System.Windows.Media.SolidColorBrush;

namespace TestUsing9283
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            Message.Background = new TheBrush(Colors.Orange);
        }
    }
}
 
C# CODE EXAMPLE created on Monday, October 12, 2009 permalink
How to create and use custom extension methods
This example shows how you can adorn custom objects with methods which read and display internal information about the object using reflection. You can see this as an alternative to inheritance which can be used if e.g. a class already inherits from another and you do not have access to the parent class. Download the project to get the ObjectReflector class which is used in this code.
using System;
using System.Collections.Generic;
using TestExtensionMethods8837.Helpers;

namespace TestExtensionMethods8837
{
    class Program
    {
        static void Main(string[] args)
        {
            List<object> objects = new List<object>();
            objects.Add(new Customer() { FirstName = "Jim", LastName = "Smith", Age = 45 });
            objects.Add(new Customer() { FirstName = "Jake", LastName = "Anders", Age = 45 });
            objects.Add(new Building() { Name = "Apartment Block #23", SquareMeters = 3874 });
            objects.Add(new Building() { Name = "East Side Apartments", SquareMeters = 3874 });
            objects.Add(new Building() { Name = "Office Suite #892", SquareMeters = 3874 });
            objects.ForEach(o => Console.WriteLine(o.Display()));
            objects.ForEach(o => Console.WriteLine(o.DisplayAdorned("Chosen")));
            Console.ReadLine();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

    public class Building
    {
        public string Name { get; set; }
        public int SquareMeters { get; set; }
    }

    public static class ExtensionMethods
    {
        public static string Display(this object obj)
        {

            ObjectReflector or = new ObjectReflector(obj);
            List<string> names = or.GetPropertyNames();

            if (names.Contains("FirstName") && names.Contains("LastName"))
            {
                return String.Format("{0}, {1}", or.GetPropertyValue<string>("LastName"), or.GetPropertyValue<string>("FirstName"));
            }
            else if (names.Contains("Name"))
            {
                return or.GetPropertyValue<string>("Name");
            }
            else
            {
                return "UNKNOWN";
            }
        }

        public static string DisplayAdorned(this object obj, string label)
        {

            ObjectReflector or = new ObjectReflector(obj);
            List<string> names = or.GetPropertyNames();

            if (names.Contains("FirstName") && names.Contains("LastName"))
            {
                return label + ": " + String.Format("{0}, {1}", or.GetPropertyValue<string>("LastName"), or.GetPropertyValue<string>("FirstName")).ToUpper();
            }
            else if (names.Contains("Name"))
            {
                return label + ": " + or.GetPropertyValue<string>("Name");
            }
            else
            {
                return "UNKNOWN";
            }
        }
    }
}
 
C# CODE EXAMPLE created on Friday, October 16, 2009 permalink
How to create a callback method
Here is a simple callback method in which you pass back an integer when the process is completed.
using System;
using System.Threading;

namespace TestCallBack89393
{
    class Program
    {
        static void Main(string[] args)
        {
            OfferManager offerManager = new OfferManager();
            Console.WriteLine("before creating offer");
            offerManager.CreateOffer("test", OnCreateOfferComplete );

            Console.ReadLine();
        }

        private static void OnCreateOfferComplete(int id)
        {
            Console.WriteLine("offer has been created with id of {0}", id);
        }
    }

    public class OfferManager
    {
        public void CreateOffer(string idCode, Action<int> onComplete)
        {
            Console.WriteLine("creating offer");
            Random random = new Random();
            int generatedId = random.Next(1000) + 1000;
            Thread.Sleep(2000);
            if (onComplete != null)
                onComplete(generatedId);
        }
    }
}
 
C# CODE EXAMPLE created on Friday, October 16, 2009 permalink
How to create and subscribe to custom events
This example shows the syntax of creating events on custom objects and then subscribing to those events.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestEventsds343
{
    public class Program
    {
        static void Main(string[] args)
        {
            Product product1 = Product.LoadProduct(222);
            EmailManager.NotifyAdministrator(product1);
            product1.OnPurchaseMade += new Product.PurchaseHandler(NotifyUser);
            product1.Purchase();

            Product product2 = Product.LoadProduct(333);
            EmailManager.NotifyAdministrator(product2);
            product2.OnPurchaseMade += new Product.PurchaseHandler(NotifyUser);
            product2.Purchase();

            Console.ReadLine();
        }

        static void NotifyUser(object sender, PurchaseArgs e)
        {
            ((Product)sender).Log();
            Console.WriteLine(e.Message);
        }
    }

    public static class EmailManager
    {
        public static void NotifyAdministrator(Product product)
        {
            product.OnPurchaseMade += new Product.PurchaseHandler(SendEmail);
        }

        public static void SendEmail(object sender, PurchaseArgs e)
        {
            Product product = sender as Product;
            Console.WriteLine("Just sent e-mail to administrator notifying of purchase of article {0}", product.ProductNumber);
        }
    }

    public class PurchaseArgs : EventArgs
    {
        public string Message { get; set; }

        public PurchaseArgs(string message)
        {
            Message = message;
        }
    }

    public class Product
    {
        public int ProductNumber { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public delegate void PurchaseHandler(object obj, PurchaseArgs args);

        public event PurchaseHandler OnPurchaseMade;

        public static Product LoadProduct(int productNumber)
        {
            List<Product> products = new List<Product>();
            products.Add(new Product { ProductNumber = 111, Name = "Intel CPU", Description = "Newest model, very fast." });
            products.Add(new Product { ProductNumber = 222, Name = "Philips Monitor", Description = "22-inch, very nice." });
            products.Add(new Product { ProductNumber = 333, Name = "Sony Camera", Description = "10 Megapixels, sharp pictures." });

            return products.Where(p => p.ProductNumber == productNumber).SingleOrDefault();
        }

        public void Purchase()
        {
            PurchaseArgs purchaseArgs = new PurchaseArgs(String.Format("The product "{0}" was just purchased.", this.Name));
            OnPurchaseMade(this, purchaseArgs);
        }

        public void Log()
        {
            Console.WriteLine("Log: #{0} purchased.", this.ProductNumber);
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, October 27, 2009 permalink
Example of C# 4.0 dynamic member lookup
This shows how in C# 4.0 you can define a parameter as dynamic and call methods on it at runtime.
using System;

namespace Test4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetLengthMessage("this will work"));
            Console.WriteLine(GetLengthMessage(new int[] { 5, 7, 3, 4 }));
            Console.WriteLine(GetLengthMessage(1000));
            Console.ReadLine();
        }

        public static string GetLengthMessage(dynamic obj)
        {
            try
            {
                return String.Format("The length of this {0} is {1}", obj.GetType().Name, obj.Length);
            }
            catch
            {
                return String.Format("This {0} does not have a length.", obj.GetType().Name);
            }
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, October 27, 2009 permalink
Example of C# 4.0 optional parameters and named arguments
This shows how in C# 4.0 has caught up with PHP with the nice feature of being able to give default values to parameters. Also note that you can specify the names of the variables in any more, very flexible.
using System;

namespace Test3
{
    class Program
    {
        static void Main(string[] args)
        {
            DisplayInfo("Jim Smith");
            DisplayInfo("Joe Johnson", "Room 782");
            DisplayInfo("Alice Rogers", "Room 323", 95);
            DisplayInfo("John Anders", score: 98);
            DisplayInfo(score: 88, name: "Angie Smith");
            Console.ReadLine();
        }

        public static void DisplayInfo(string name, string classroom = "Unknown", int score = 0)
        {
            Console.WriteLine(@"Person: {0} in class ""{1}"" with score {2}", name, classroom, score );
        }
    }
}

 
C# CODE EXAMPLE created on Friday, November 06, 2009 permalink
How to get data from mutiple database tables via LINQ
This shows you the simplest way to get data out of your LINQ-to-SQL classes via LINQ. Note that we send the DataContext down into the method that gets the data via the database otherwise you do not have access to the deeper properties, e.g. Customer.
using System;
using System.Collections.Generic;
using System.Linq;
using TestExtn2343.Models;

namespace TestExtn2343
{
    class Program
    {
        public static void Main(string[] args)
        {
            using (MainDataContext db = new MainDataContext())
            {
                GetOrders(db, 10, 10).ForEach(x => Console.WriteLine("{0}, {1}", x.OrderID, x.Customer.ContactName.ToString()));
            }
            Console.ReadLine();
        }

        public static List<Order> GetOrders(MainDataContext db, int skip, int take)
        {
            List<Order> orders = (from order in db.Orders
                                    select order).Skip(skip).Take(take).ToList();
            return orders;
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, November 11, 2009 permalink
How to create objects based on strings with Activator.CreateInstance
This example shows how to instantiate classes based on the string name of the class. This would allow you to parse a text file, e.g. xml, which dynamically loads specific classes. In this example, pages are loaded and shown in a "menu".
using System;
using System.Collections.Generic;
using System.Text;

namespace TestInstant
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> pageItemsIdCodes = new List<string>() { "PageItem1", "PageItem2" };
            PageItemManager pageItemManager = new PageItemManager(pageItemsIdCodes);
            pageItemManager.DisplayMenu();

            Console.ReadLine();
        }
    }

    class PageItemManager
    {
        private Dictionary<string, BasePageItem> PageItemRecords = new Dictionary<string, BasePageItem>();
        public PageItemManager(List<string> pageItemsIdCodes)
        {
            foreach (string pageItemIdCode in pageItemsIdCodes)
            {
                Type t = Type.GetType("TestInstant." + pageItemIdCode);
                BasePageItem pageItem = (BasePageItem)Activator.CreateInstance(t, new Object[] { this });
                PageItemRecords.Add(pageItemIdCode, pageItem);
            }
        }

        public void DisplayMenu()
        {
            foreach (var pageItemRecord in PageItemRecords)
            {
                Console.WriteLine(pageItemRecord.Value.Title);
            }
        }
    }

    class BasePageItem
    {
        public string Title { get; set; }
        protected PageItemManager pageItemManager;
        public BasePageItem(PageItemManager pageItemManager)
        {
            this.pageItemManager = pageItemManager;
        }
    }

    class PageItem1 : BasePageItem
    {
        public PageItem1(PageItemManager pageItemManager)
            : base(pageItemManager)
        {
            Title = "This is page one.";
        }
    }

    class PageItem2 : BasePageItem
    {
        public PageItem2(PageItemManager pageItemManager)
            : base(pageItemManager)
        {
            Title = "This is page two.";

        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, November 24, 2009 permalink
How to pass a where clause to a method to dynamically include in a LINQ statement
This example shows you how to you can pass a where-clause as a parameter to a method which then includes this where clause dynamically in a LINQ statement.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestDynamicLinq2343
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = Customer.GetCustomers();

            Func<Customer, bool> whereClause = c => c.LastName.ToUpper().Contains("A") && c.FirstName.ToUpper().Contains("J");

            foreach (var customer in Customer.GetFilteredCustomers(customers, whereClause))
            {
                Console.WriteLine(customer.LastName);
            }

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { FirstName = "Jim", LastName = "Jones" });
            customers.Add(new Customer { FirstName = "Joe", LastName = "Adams" });
            customers.Add(new Customer { FirstName = "Jake", LastName = "Johnson" });
            customers.Add(new Customer { FirstName = "Angie", LastName = "Reckar" });
            customers.Add(new Customer { FirstName = "Jean", LastName = "Anderson" });
            return customers;
        }

        public static List<Customer> GetFilteredCustomers(List<Customer> customers, Func<Customer, bool> whereClause)
        {
            return customers
                     .Where(whereClause).ToList();
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, November 24, 2009 permalink
C# syntax for abstract, override, virtual, base
The C# syntax of overriding classes and calling inherited parent classes differs than that of PHP ("don't forget virtual" and "base instead of parent"), so I did this example for future reference.
using System;

namespace TestOverride8234
{
    class Program
    {
        static void Main(string[] args)
        {
            CorporateCustomer corporateCustomer = new CorporateCustomer(11);
            Console.WriteLine("---");
            PrivateCustomer privateCustomer = new PrivateCustomer(22);
            Console.WriteLine("---");
            OtherCustomer otherCustomer = new OtherCustomer(33);

            Console.ReadLine();
        }
    }

    public abstract class Customer
    {
        protected int id;

        public Customer(int id)
        {
            this.id = id;
            Console.WriteLine("in BASE customer constructor");
        }

        protected virtual void Initialize()
        {
            Console.WriteLine("initialized BASE customer, id={0}", id);
        }
    }

    public class PrivateCustomer : Customer
    {
        public PrivateCustomer(int id) : base(id)
        {
            Console.WriteLine("in PRIVATE customer constructor");
            Initialize();
        }

        protected override void Initialize()
        {
            Console.WriteLine("initialized PRIVATE customer, id={0}", id);
        }
    }

    public class CorporateCustomer : Customer
    {
        public CorporateCustomer(int id)
            : base(id)
        {
            Console.WriteLine("in CORPORATE customer constructor");
            Initialize();
        }

        protected override void Initialize()
        {
            base.Initialize();
            Console.WriteLine("initialized CORPORATE customer, id={0}", id);
        }
    }

    public class OtherCustomer : Customer
    {
        public OtherCustomer(int id)
            : base(id)
        {
            Console.WriteLine("in OTHER customer constructor");
            Initialize();
        }
    }
}
 
C# CODE EXAMPLE created on Friday, December 04, 2009 permalink
Custom method that processes a collection of objects dynamically
This is beginning code if you need to, e.g. create a DataGrid that accepts a List<T> of any type of object, and a list of fields, and displays these based on the fields.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TestSmartGrid2342
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> columnFields = new List<string> { "LastName", "FirstName", "ZipCode" };
            List<Customer> customers = Customer.GetCustomers();

            FillSmartGrid(customers.Cast<object>().ToList(), columnFields);

            Console.ReadLine();
        }

        public static void FillSmartGrid(List<object> items, List<string> columnFields)
        {
            foreach (var item in items)
            {
                ObjectReflector or = new ObjectReflector(item);

                foreach (string columnField in columnFields)
                {
                    Console.WriteLine(columnField + ": " + or.GetPropertyValue<string>(columnField));
                }
                Console.WriteLine("---");
            }
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { FirstName = "Jim", LastName = "Jones", ZipCode = "23434" });
            customers.Add(new Customer { FirstName = "Joe", LastName = "Adams", ZipCode = "12312" });
            customers.Add(new Customer { FirstName = "Jake", LastName = "Johnson", ZipCode = "23111" });
            customers.Add(new Customer { FirstName = "Angie", LastName = "Reckar", ZipCode = "54343" });
            customers.Add(new Customer { FirstName = "Jean", LastName = "Anderson", ZipCode = "16623" });
            return customers;
        }
    }

    public class ObjectReflector
    {
        private object theObject;
        private Type theType { get; set; }
        private PropertyInfo[] thePropertyInfo;
        private List<string> thePropertyNames = new List<string>();
        private Dictionary<string, Type> thePropertyTypes = new Dictionary<string, Type>();

        public ObjectReflector(object o)
        {
            theObject = o;
            theType = theObject.GetType();
            thePropertyInfo = theType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            for (int i = 0; i < thePropertyInfo.Length; i++)
            {
                PropertyInfo propInfo = (PropertyInfo)thePropertyInfo[i];
                thePropertyNames.Add(propInfo.Name);
                thePropertyTypes.Add(propInfo.Name, propInfo.PropertyType);
            }
        }

        public string GetPropertyNameAndTypeList()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < thePropertyInfo.Length; i++)
            {
                PropertyInfo propInfo = (PropertyInfo)thePropertyInfo[i];
                sb.Append(String.Format("{0} ({1}){2}", propInfo.Name, propInfo.PropertyType, Environment.NewLine));
            }
            return sb.ToString();
        }

        public List<string> GetPropertyNames()
        {
            return thePropertyNames;
        }

        public string GetObjectShortName()
        {
            return theObject.GetType().Name;
        }

        public string GetObjectLongName()
        {
            return theObject.GetType().ToString();
        }

        public T GetPropertyValue<T>(string propertyName)
        {
            return (T)theType.GetProperty(propertyName).GetValue(theObject, null);
        }

        public string GetPropertyValueAsString(string propertyName)
        {
            if (theType.GetProperty(propertyName).GetValue(theObject, null) == null)
                return "";
            else
                return theType.GetProperty(propertyName).GetValue(theObject, null).ToString();
        }

        public T GetMethodValue<T>(string methodName, object[] parameters)
        {
            return (T)theType.GetMethod(methodName).Invoke(theObject, parameters);
        }

        public int GetNumberOfProperties()
        {
            return thePropertyInfo.Length;
        }

        public bool PropertyExists(string propertyName)
        {
            if (thePropertyNames.Contains(propertyName))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public Type GetPropertyType(string propertyName)
        {
            if (PropertyExists(propertyName))
            {
                return thePropertyTypes[propertyName];
            }
            else
            {
                return null;
            }
        }

        public void SetPropertyValue<T>(string propertyName, T value)
        {
            theType.GetProperty(propertyName).SetValue(theObject, value, null);
        }
    }
}
 
C# CODE EXAMPLE created on Friday, December 04, 2009 permalink
How to use Cast<T> to cast generic Lists of objects
Since C# 3.0 doesn't inherently support co-variance and contra-variance, you can't just send a List<Customer> as a parameter to a method that accepts List<object> and expect it to cast automatically. But by running it through Cast<T>, it is easy enough, here's how.
using System.Collections.Generic;
using System.Linq;
using System;

namespace TestCast2343
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> strings = new List<string> { "one", "two", "three" };
            List<int> ints = new List<int> { 34, 35, 36 };
            List<Customer> customers = Customer.GetCustomers();

            ProcessCollectionDynamicallyWithReflection(strings.Cast<object>().ToList());
            ProcessCollectionDynamicallyWithReflection(ints.Cast<object>().ToList());
            ProcessCollectionDynamicallyWithReflection(customers.Cast<object>().ToList());

            Console.ReadLine();
        }

        static void ProcessCollectionDynamicallyWithReflection(List<object> items)
        {
            foreach (var item in items)
            {
                Console.WriteLine(item.GetType().Name);
            }
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { FirstName = "Jim", LastName = "Jones", ZipCode = "23434" });
            customers.Add(new Customer { FirstName = "Joe", LastName = "Adams", ZipCode = "12312" });
            customers.Add(new Customer { FirstName = "Jake", LastName = "Johnson", ZipCode = "23111" });
            customers.Add(new Customer { FirstName = "Angie", LastName = "Reckar", ZipCode = "54343" });
            customers.Add(new Customer { FirstName = "Jean", LastName = "Anderson", ZipCode = "16623" });
            return customers;
        }
    }
}
 
C# CODE EXAMPLE created on Friday, December 04, 2009 permalink
How to mix abstract and virtual methods in a C# class
You may have thought that abstract classes cannot have methods with executable code but they can, and hence, you can have classes with both abstract and virtual methods in them, which comes in handy as this example shows.
using System;
using System.Collections.Generic;

namespace TestSql28374
{
    class Program
    {
        static void Main(string[] args)
        {
            object item = new object();
            List<string> properties = new List<string>();

            SqlCreateStatement sqlCreateStatement = new SqlCreateStatement(properties);
            sqlCreateStatement.Execute();

            SqlInsertStatement sqlInsertStatement = new SqlInsertStatement(item, properties);
            sqlInsertStatement.Execute();

            Console.ReadLine();
        }
    }

    public abstract class SqlStatement
    {
        protected List<string> properties;
        protected object item;
        protected string sql;

        public SqlStatement(List<string> properties)
        {
            this.properties = properties;
        }

        protected abstract void Initialize();

        public virtual void Execute()
        {
            Console.WriteLine("Sending to database: " + sql);
        }
    }

    public class SqlCreateStatement : SqlStatement
    {

        public SqlCreateStatement(List<string> properties)
            : base(properties)
        {
            Initialize();
        }

        protected override void Initialize()
        {
            sql = "CREATE TABLE...";
        }
    }

    public class SqlInsertStatement : SqlStatement
    {
        public SqlInsertStatement(object item, List<string> properties)
            : base(properties)
        {
            this.item = item;

            Initialize();
        }

        protected override void Initialize()
        {
            sql = "INSERT INTO...";
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, December 16, 2009 permalink
How to creare a generic factory method to clone an inherited object
This example shows how to start building a reflector class which analyzes an object (here an object derived from Item) and create a clone of it. Notice the where T : new() which you need if you are going to instantiate the generic object in the method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestGeneric8282
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.FirstName = "Jim";
            ItemReflector irCustomer = new ItemReflector(customer);
            Customer customerClone = irCustomer.GetClone<Customer>();

            Console.WriteLine("customer: " + customer.FirstName);
            Console.WriteLine("customer clone: " + customerClone.FirstName);

            customerClone.FirstName = "JAMES";
            Console.WriteLine("...customer clone CHANGED...");

            Console.WriteLine("customer: " + customer.FirstName);
            Console.WriteLine("customer clone: " + customerClone.FirstName);

            Console.ReadLine();
        }
    }

    public abstract class Item
    {
        ///
    }

    public class Customer : Item
    {
        public string FirstName { get; set; }
    }

    public class Address : Item
    {
        //...
    }

    public class ItemReflector
    {
        private Item item;

        public ItemReflector(Item item)
        {
            this.item = item;
        }

        public T GetClone<T>() where T : new()
        {
            T clonedItem = new T();

            //...manipulate the clonedItem with reflection...
            Type theType = clonedItem.GetType();
            theType.GetProperty("FirstName").SetValue(clonedItem, (item as Customer).FirstName, null);

            return clonedItem;
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, January 12, 2010 permalink
How to serialize from object to string and deserialize from string to object
This example has two reusable methods that make serialization and deserialization between object and string one line statements.
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;

namespace TestSerialize2342
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = Customer.GetCustomers();

            Console.WriteLine("--- Serializing ------------------");

            foreach (var customer in customers)
            {
                Console.WriteLine("Serializing " + customer.GetFullName() + "...");
                string xml = XmlHelpers.SerializeObject<Customer>(customer);
                Console.WriteLine(xml);
                Console.WriteLine("Deserializing ...");
                Customer customer2 = XmlHelpers.DeserializeObject<Customer>(xml);
                Console.WriteLine(customer2.GetFullName());
                Console.WriteLine("---");
            }

            Console.ReadLine();
        }

    }

    public static class StringHelpers
    {
        public static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        public static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
    }

    public static class XmlHelpers
    {
        public static string SerializeObject<T>(object o)
        {
            MemoryStream ms = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8);
            xs.Serialize(xtw, o);
            ms = (MemoryStream)xtw.BaseStream;
            return StringHelpers.UTF8ByteArrayToString(ms.ToArray());
        }

        public static T DeserializeObject<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(StringHelpers.StringToUTF8ByteArray(xml));
            XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8);
            return (T)xs.Deserialize(ms);
        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        private int internalValue = 23;

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { Id = 1, FirstName = "Jim", LastName = "Jones", ZipCode = "23434" });
            customers.Add(new Customer { Id = 2, FirstName = "Joe", LastName = "Adams", ZipCode = "12312" });
            customers.Add(new Customer { Id = 3, FirstName = "Jack", LastName = "Johnson", ZipCode = "23111" });
            customers.Add(new Customer { Id = 4, FirstName = "Angie", LastName = "Reckar", ZipCode = "54343" });
            customers.Add(new Customer { Id = 5, FirstName = "Henry", LastName = "Anderson", ZipCode = "16623" });
            return customers;
        }

        public string GetFullName()
        {
            return FirstName + " " + LastName + "(" + internalValue + ")";
        }

    }
}
 
C# CODE EXAMPLE created on Friday, January 15, 2010 permalink
How to serialize and deserialize an object
This solution using XmlWriter/XmlReader is a simpler solution than this example using XmlTextWriter and UTF8Encoding.
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
using System.Xml.Linq;
using System.Linq;

namespace TestSerialize2342
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = Customer.GetCustomers();
            Console.WriteLine("--- Serializing ------------------");
            foreach (var customer in customers)
            {
                Console.WriteLine("Serializing " + customer.GetFullName() + "...");
                string xml = XmlHelpers.SerializeObject<Customer>(customer);
                XDocument xdoc = XDocument.Parse(xml);
                var firstNameElement = (from e in xdoc.Root.Elements()
                                 where e.Name == "FirstName"
                                 select e).Single();
                Console.WriteLine("First Name = " + firstNameElement.Value);
            }
            Console.ReadLine();
        }
    }

    public static class XmlHelpers
    {
        public static string SerializeObject<T>(object obj)
        {
            StringBuilder sb = new StringBuilder();
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            using (XmlWriter xWriter = XmlWriter.Create(sb))
            {
                xs.Serialize(xWriter, obj);
                xWriter.Flush();
                return sb.ToString();
            }
        }

        public static T DeserializeObject<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(xml);
            XmlReader xr = XmlReader.Create(sr);
            return (T)xs.Deserialize(xr);
        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }

        private int internalValue = 23;

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { Id = 1, FirstName = "Jim", LastName = "Jones", ZipCode = "23434" });
            customers.Add(new Customer { Id = 2, FirstName = "Joe", LastName = "Adams", ZipCode = "12312" });
            customers.Add(new Customer { Id = 3, FirstName = "Jack", LastName = "Johnson", ZipCode = "23111" });
            customers.Add(new Customer { Id = 4, FirstName = "Angie", LastName = "Reckar", ZipCode = "54343" });
            customers.Add(new Customer { Id = 5, FirstName = "Henry", LastName = "Anderson", ZipCode = "16623" });
            return customers;
        }

        public string GetFullName()
        {
            return FirstName + " " + LastName + "(" + internalValue + ")";
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, January 27, 2010 permalink
How to make StringBuilder have a .Clear() method
During the last decade everytime I wanted to clear a StringBuilder I had to look around for the code to do it (sb.Remove(0,sb.Length)), but if you put this in an extension method, you can simply call sb.Clear() to clear a StringBuilder.
using System;
using System.Text;

namespace TestStringBuil234
{
    public class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("one,");
            sb.Append("two");
            Console.WriteLine("[" + sb.ToString() + "]");
            sb.Clear();
            Console.WriteLine("[" + sb.ToString() + "]");

            Console.ReadLine();
        }
    }

    public static class StringHelpers
    {
        public static StringBuilder Clear(this StringBuilder sb)
        {
            return sb.Remove(0, sb.Length);
        }
    }
}
 
C# CODE EXAMPLE created on Saturday, January 30, 2010 permalink
How to create a generic method to return a specific type specified by the call
This method allows the caller to specify the type of variable he knows he will be getting, useful e.g. if you are doing reflection and only the caller knows what types to expect from a generic method. There is a discussion at stackoverflow on where most people say that this example is a "misuse of generics", interesting, since it is a solution done in less code with the same outcome.
using System;
using System.Collections.Generic;

namespace TestGener234
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Item> items = Item.GetItems();
            foreach (var item in items)
            {
                string firstName = item.GetPropertyValue<string>("firstName");
                int age = item.GetPropertyValue<int>("age");
                Console.WriteLine("First name is {0} and age is {1}.", firstName, age);
            }
            Console.ReadLine();
        }
    }

    public class Item
    {
        public string FirstName { get; set; }
        public string Age { get; set; }


        public static List<Item> GetItems()
        {
            List<Item> items = new List<Item>();
            items.Add(new Item { FirstName = "Jim", Age = "34" });
            items.Add(new Item { FirstName = "Angie", Age = "32" });
            return items;
        }

        public T GetPropertyValue<T>(string propertyIdCode)
        {
            if (propertyIdCode == "firstName")
                return (T)(object)FirstName;
            if (propertyIdCode == "age")
                return (T)(object)(Convert.ToInt32(Age));
            return default(T);
        }
    }
}
 
C# CODE EXAMPLE created on Saturday, February 06, 2010 permalink
Base code to create a simple regex unit tester
Here's some base code I use when I've written a regex and need to test it with positive and negative cases as I tweak it.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Testreg2342
{
    public class Program
    {
        static void Main(string[] args)
        {
            bool unitTestPassed = true;

            List<string> goodEntries = new List<string>
            {
                "2008-12-22"
            };

            List<string> badEntries = new List<string>
            {
                "2010-12-12X",
                "2010-12-32 12:00:00"
            };

            foreach (var entry in goodEntries)
            {
                if (entry.IsValidDateFormat())
                    Console.WriteLine("ok: good entry correctly passed: " + entry);
                else
                {
                    Console.WriteLine("**FAIL** GOOD ENTRY INCORRECTLY DID NOT PASS: " + entry);
                    unitTestPassed = false;
                }
            }

            foreach (var entry in badEntries)
            {
                if (!entry.IsValidDateFormat())
                    Console.WriteLine("ok: bad entry corrcectly did not pass : " + entry);
                else
                {
                    Console.WriteLine("**FAIL** BAD ENTRY INCORRECTLY PASSED: " + entry);
                    unitTestPassed = false;
                }
            }

            Console.WriteLine();
            if(unitTestPassed)
                Console.WriteLine("unit test passed");
            else
                Console.WriteLine("UNIT TEST FAILED, CORRECT ALL ENTRIES MARKED **FAIL** ABOVE!");

            Console.ReadLine();

        }
    }

    public static class StringHelpers
    {
        public static bool IsValidDateFormat(this string purportedDateFormat)
        {
            return RegexHelpers.Matches(purportedDateFormat, @"^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$");
        }
    }

    public static class RegexHelpers
    {

        //use if you are expecting only one match, e.g. from "id = ???"
        public static string GetMatch(string text, string regex)
        {
            Match match = Regex.Match(text, regex);
            if (match.Success)
            {
                string theMatch = match.Groups[0].Value;
                return theMatch;
            }
            else
            {
                return null;
            }
        }

        public static bool Matches(string text, string regex)
        {
            if (GetMatch(text, regex) != null)
                return true;
            else
                return false;
        }
    }
}
 
C# CODE EXAMPLE created on Monday, February 22, 2010 permalink
How to check for first and last items in a foreach loop
This was one of the the many interesing ideas for avoiding index counter messiness in foreach loops. This reads nicely for short lists, e.g. dropdown/radiobutton collections, etc. but it is not resourceful for large lists (because .last() iterates through the collection) and it assumes all values are unique.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestForEach23433
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string> { "Smith", "Jones", "Rogers", "Anderson" };

            var first = names.First();
            var last = names.Last();
            foreach (var name in names)
            {
                Console.Write(name);

                if (name == first)
                    Console.WriteLine(" (first)");
                else if (name == last)
                    Console.WriteLine(" (last)");
                else
                    Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Sunday, March 07, 2010 permalink
How to use NameValueCollection for a collection of items with both single and multiple keys
I needed a collection type to easily lookup values with multiple, identical keys and since I was just storing strings, the non-generic NameValueCollection was exactly what I needed, here's an example of what it can do. This example assumes you know which keys are singular and multiple in your collection. Note that if you use .Get() on a multiple key, it will nicely return a comma-delimited string.
using System;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

namespace TestMultipleKeyDictionary8282
{
    public class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection variables = new NameValueCollection();

            variables.Add("title", "Report #3");
            variables.Add("description", "This is the description.");
            variables.Add("note", "more information is available from marketing");
            variables.Add("note", "time limit for this project is 18 hours");
            variables.Add("todo", "expand the outline");
            variables.Add("todo", "work on the introduction");
            variables.Add("todo", "lookup footnotes");

            string[] singleVariableNames = { "title", "subtitle", "description", "author", "datePublished" };
            string[] multipleVariableNames = { "note", "todo", "info" };

            foreach (var singleVariableName in singleVariableNames)
            {
                if (variables.Get(singleVariableName) != null)
                    Console.WriteLine("{0,-15} {1}", singleVariableName, variables.Get(singleVariableName));
                else
                    Console.WriteLine("{0,-15} {1}", singleVariableName, "N/A");
            }

            foreach (var multipleVariableName in multipleVariableNames)
            {
                if (variables.Get(multipleVariableName) != null)
                    variables.GetValues(multipleVariableName).ToList().ForEach(v => Console.WriteLine("{0,-15} {1}", multipleVariableName, v));
                else
                    Console.WriteLine("{0,-15} {1}", multipleVariableName, "N/A");
            }

            ShowEntries(variables);
            variables.Remove("todo");
            ShowEntries(variables);
            variables.Clear();
            ShowEntries(variables);

            Console.ReadLine();
        }

        public static void ShowEntries(NameValueCollection nvc)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < nvc.Keys.Count; i++)
            {
                sb.Append(nvc.Keys[i] + ", ");        
            }
            Console.WriteLine("There are {0} kinds of keys: {1}", nvc.Count, sb.ToString().TrimEnd(new char[] {',',' '}));
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, March 16, 2010 permalink
How to use OrderedDictionary to lookup items by string key or integer index
I had created a Dictionary with which I could lookup items by their string key but then I also needed to lookup the items by their integer index as well. This unfornately doesn't work with Dictionary since it is not an ordered list, but the non-generic OrderedDictionary worked nicely in my case, I just had to do the appropriate casting. You might also check at the above link for more ideas, e.g. inherit from KeyedCollection<TKey, TItem>.
using System;
using System.Collections.Specialized;

namespace TestOrderedDictionary882234
{
    class Program
    {
        static void Main(string[] args)
        {
            OrderedDictionary events = new OrderedDictionary();

            events.Add("first", "this is the first one");
            events.Add("second", "this is the second one");
            events.Add("third", "this is the third one");

            string description1 = events["first"].ToString();
            Console.WriteLine(description1);

            string description2 = events[1].ToString();
            Console.WriteLine(description2);

            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Wednesday, May 12, 2010 permalink
How to create and subscribe to custom events using EventHandler
This example shows the syntax of creating events on custom objects and then subscribing to those events. It is a simpler example than this example which used delegate, thanks Konrad.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestEvents288202
{
    class Program
    {
        static void Main(string[] args)
        {
            Product product1 = Product.LoadProduct(222);
            EmailManager.NotifyAdministrator(product1);
            product1.OnPurchaseMade += NotifyUser;
            product1.Purchase();

            Product product2 = Product.LoadProduct(333);
            EmailManager.NotifyAdministrator(product2);
            product2.OnPurchaseMade += NotifyUser;
            product2.Purchase();

            Console.ReadLine();
        }

        static void NotifyUser(object sender, PurchaseArgs e)
        {
            ((Product)sender).Log();
            Console.WriteLine(e.Message);
        }
    }

    public static class EmailManager
    {
        public static void NotifyAdministrator(Product product)
        {
            product.OnPurchaseMade += SendEmail;
        }

        public static void SendEmail(object sender, PurchaseArgs e)
        {
            Product product = sender as Product;
            Console.WriteLine("Just sent e-mail to administrator notifying of purchase of article {0}", product.ProductNumber);
        }
    }

    public class PurchaseArgs : EventArgs
    {
        public string Message { get; set; }

        public PurchaseArgs(string message)
        {
            Message = message;
        }
    }

    public class Product
    {
        public int ProductNumber { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public event EventHandler<PurchaseArgs> OnPurchaseMade;


        public static Product LoadProduct(int productNumber)
        {
            List<Product> products = new List<Product>();
            products.Add(new Product { ProductNumber = 111, Name = "Intel CPU", Description = "Newest model, very fast." });
            products.Add(new Product { ProductNumber = 222, Name = "Philips Monitor", Description = "22-inch, very nice." });
            products.Add(new Product { ProductNumber = 333, Name = "Sony Camera", Description = "10 Megapixels, sharp pictures." });

            return products.Where(p => p.ProductNumber == productNumber).SingleOrDefault();
        }

        public void Purchase()
        {
            PurchaseArgs purchaseArgs = new PurchaseArgs(String.Format("The product '{0}' was just purchased.", this.Name));
            OnPurchaseMade(this, purchaseArgs);
        }

        public void Log()
        {
            Console.WriteLine("Log: #{0} purchased.", this.ProductNumber);
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, June 01, 2010 permalink
How to strip off e.g. "note:" and "firstName: " from the left of a string using regex
This codes shows how you can use regular expressions to strip off a "label + colon" from a line e.g. if you are parsing through lines labels with codes on the left.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TestRegex8822
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lines = new List<string>();
            lines.Add("note: this is a note");
            lines.Add("test:    just a test");
            lines.Add("test:tttjust a test");
            lines.Add("firstName: Jim"); //"firstName" IS a label because it does NOT contain a space
            lines.Add("first name: Jim"); //"first name" is not a label because it contains a space
            lines.Add("description: this is the first description");
            lines.Add("description:this is the second description"); //no space after colon
            lines.Add("this is a line with no label");
            lines.Add("she said to him: follow me");

            foreach (var line in lines)
            {
                LabelLinePair llp = line.GetLabelLinePair();
                Console.WriteLine(llp.Label);
                Console.WriteLine(llp.Line);
                Console.WriteLine("--");
            }
            Console.ReadLine();
        }
    }

    public static class StringHelpers
    {
        public static LabelLinePair GetLabelLinePair(this string line)
        {
            Regex regex = new Regex(@"(?<label>.+):s*(?<text>.+)");
            Match match = regex.Match(line);
            LabelLinePair llp = new LabelLinePair();
            llp.Label = match.Groups["label"].ToString();
            llp.Line = match.Groups["text"].ToString();

            if (llp.Label.IsNullOrEmpty() || llp.Label.Contains(" "))
            {
                llp.Label = "";
                llp.Line = line;
            }

            return llp;
        }

        public static bool IsNullOrEmpty(this string line)
        {
            return String.IsNullOrEmpty(line);
        }
    }

    public class LabelLinePair
    {
        public string Label { get; set; }
        public string Line { get; set; }
    }
}
 
C# CODE EXAMPLE created on Friday, June 11, 2010 permalink
How to override events in inherited classes
This shows you how to have each inheriting class handle its own events and sent its own object back up to the subscriber.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestInheritedEvents234
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.OnDeleted += new EventHandler(person_OnDeleted);
            person.Delete();

            Customer customer = new Customer();
            customer.OnDeleted += new EventHandler(person_OnDeleted);
            customer.Delete();

            Console.ReadLine();
        }

        static void person_OnDeleted(object sender, EventArgs e)
        {
            Console.WriteLine("in main program: the object sent was a " + sender.GetType().Name);
        }
    }

    public class Person
    {
        public virtual event EventHandler OnDeleted;

        public virtual void Delete()
        {
            Console.WriteLine("inside person: deleted");
            if(OnDeleted != null)
                OnDeleted(this, null);
        }
    }

    public class Customer : Person
    {
        public override event EventHandler OnDeleted;

        public override void Delete()
        {
            Console.WriteLine("inside customer: deleted");
            if (OnDeleted != null)
                OnDeleted(this, null);
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, June 15, 2010 permalink
How to set a nullable type to null in a ternary operator
If you try to set e.g. a nullable int to null in a ternary operator, you get the error "there is no implicit conversion between null and int". Instead of assigning it to "null" assign it to default(int?). You can read more about why here. Here is an example with Guid.
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string agencyGuid = "";
            Guid? guid = new Guid();

            //this compiles:
            if (String.IsNullOrEmpty(agencyGuid))
                guid = null;
            else
                guid = new Guid(agencyGuid);

            //this compiles:
            guid = String.IsNullOrEmpty(agencyGuid) ? new Guid() : new Guid(agencyGuid);

            //but this gives the error: "there is no implicit conversion between null and System.Guid"
            guid = String.IsNullOrEmpty(agencyGuid) ? null : new Guid(agencyGuid);

            //so you have to use default()
            guid = String.IsNullOrEmpty(agencyGuid) ? default(Guid?) : new Guid(agencyGuid);

            Console.WriteLine(guid.ToString());
            Console.ReadLine();
        }
    }
}
 
C# CODE EXAMPLE created on Saturday, June 26, 2010 permalink
How to use a custom parameter struct to pass any number of variables to constructors of similar classes.
This shows a common pattern to pass in a collection of unlike typed variables into constructors of similar classes, the inherited class of which saves the common variables locally while each asy then unpacks each of its specific variables. Putting all variables in a custom struct like this enables you to avoid the runtime recasting of the variables that a Dictionary<string,object> solution would cause.
using System;
using System.Collections.Generic;
using System.Text;

namespace TestPass234
{
    class Program
    {
        static void Main(string[] args)
        {
            List<SectionItem> sectionItems = new List<SectionItem>();

            {
                SectionItemParameters vars = new SectionItemParameters();
                vars.SectionNumber = 1;
                vars.Title = "Lesson #1";
                vars.StartDate = new DateTime(2008, 12, 25);
                List<Flashcard> flascards = new List<Flashcard>();
                flascards.Add(new Flashcard { Question = "What color is the sky?", Answer = "blue" });
                flascards.Add(new Flashcard { Question = "What color is the sun?", Answer = "yellow" });
                vars.Flashcards = flascards;
                SectionItem sectionItem = SectionItem.Instantiate("lesson", vars);
                sectionItems.Add(sectionItem);
            }

            {
                SectionItemParameters vars = new SectionItemParameters();
                vars.Title = "Info #1";
                vars.Content = "This is info number one.";
                SectionItem sectionItem = SectionItem.Instantiate("info", vars);
                sectionItems.Add(sectionItem);
            }

            foreach (var sectionItem in sectionItems)
            {
                Console.WriteLine(sectionItem.Render());
            }
            Console.ReadLine();
        }
    }

    public class SectionItem
    {
        protected string _title;

        public SectionItem()
        { }

        public SectionItem(SectionItemParameters vars)
        {
            _title = vars.Title;
        }

        public static SectionItem Instantiate(string idCode, SectionItemParameters vars)
        {
            switch (idCode)
            {
                case "lesson":
                    return new SectionItemLesson(vars);
                case "info":
                    return new SectionItemInfo(vars);
                default:
                    return new SectionItem();
            }
        }

        public virtual string Render()
        {
            return "undefined section item";
        }

    }


    public class SectionItemLesson : SectionItem
    {
        private int _sectionNumber;
        private DateTime _startDate;
        private List<Flashcard> _flashcards = new List<Flashcard>();

        public SectionItemLesson(SectionItemParameters vars)
            : base(vars)
        {
            _sectionNumber = vars.SectionNumber;
            _startDate = vars.StartDate;
            _flashcards = vars.Flashcards;
        }

        public override string Render()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(String.Format(">>> {0}. {1} (Starts {2:ddd, MMM d, yyyy})", _sectionNumber, _title, _startDate));
            foreach (var flashcard in _flashcards)
                sb.AppendLine("    - " + flashcard.Render());
            return sb.ToString();
        }
    }

    public class SectionItemInfo : SectionItem
    {
        private string _content;

        public SectionItemInfo(SectionItemParameters vars)
            : base(vars)
        {
            _content = vars.Content;
        }

        public override string Render()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(String.Format(">>> {0}", _title));
            sb.AppendLine(String.Format("    {0}", _content));
            return sb.ToString();
        }
    }

    public class Flashcard
    {
        public string Question { get; set; }
        public string Answer { get; set; }

        public string Render()
        {
            return "Q: " + Question + " A: " + Answer;
        }
    }

    public struct SectionItemParameters
    {
        public string Title { get; set; }
        public int SectionNumber { get; set; }
        public DateTime StartDate { get; set; }
        public List<Flashcard> Flashcards { get; set; }
        public string Content { get; set; }
    }
}
 
C# CODE EXAMPLE created on Wednesday, June 30, 2010 permalink
How to encode binary files to text files and back to binary again
This shows you how you can take e.g. png, jpg, mp3 files and convert them to text, for example if you want to transport them via plain text, and then on the other site turn them back into their original binary format.
using System;
using System.IO;
using System.Text;

namespace TestEnc23833
{
    class Program
    {
        static void Main(string[] args)
        {

            FileHelpers.EncodeBinaryFileToTextFile(@"C:testenctest.png", @"C:testenctest.txt");
            FileHelpers.DecodeTextFileFromBinaryFile(@"C:testenctest.txt", @"C:testenctestcopy.png");

            Console.WriteLine("finished");
            Console.ReadLine();
        }
    }

    public static class FileHelpers
    {
        public static void EncodeBinaryFileToTextFile(string inputFileName, string outputFileName)
        {
            FileStream inFile = new FileStream(inputFileName, FileMode.Open, FileAccess.Read);
            byte[] binaryData = new Byte[inFile.Length];
            long bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length);
            inFile.Close();
            string base64String = Convert.ToBase64String(binaryData, 0, binaryData.Length);
            StreamWriter outFile = new StreamWriter(outputFileName, false, Encoding.ASCII);
            outFile.Write(base64String);
            outFile.Close();
        }

        public static void DecodeTextFileFromBinaryFile(string inputFileName, string outputFileName)
        {
            StreamReader inFile = new StreamReader(inputFileName, Encoding.ASCII);
            char[] base64CharArray = new char[inFile.BaseStream.Length];
            inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length);
            string base64String = new string(base64CharArray);
            byte[] binaryData = Convert.FromBase64String(base64String);
            FileStream outFile = new FileStream(outputFileName, FileMode.Create, FileAccess.Write);
            outFile.Write(binaryData, 0, binaryData.Length);
            outFile.Close();
        }
    }
}
 
C# CODE EXAMPLE created on Friday, July 02, 2010 permalink
Generic method to case-insensitively convert a string to any enum
This generic static method takes an enum type and a string and converts it, ignoring case, and if the string is invalid, it will return the first (default) item in the enum collection. I'm returning the default value in a catch since IsDefined doesn't have an ignoreCase parameter, but there are more elegant ways to do this, especially in C#4 .
using System;

namespace TestEnum2934234
{
    class Program
    {
        static void Main(string[] args)
        {
            LessonStatus lessonStatus = StringHelpers.ConvertStringToEnum<LessonStatus>("pxrepared");
            ReportStatus reportStatus = StringHelpers.ConvertStringToEnum<ReportStatus>("finished");

            Console.WriteLine(lessonStatus.ToString());
            Console.WriteLine(reportStatus.ToString());
            Console.ReadLine();
        }
    }

    public static class StringHelpers
    {
        public static T ConvertStringToEnum<T>(string text)
        {
            try
            {
                return (T)Enum.Parse(typeof(T), text, true);
            }
            catch (ArgumentException ex)
            {
                return default(T);
            }
        }
    }

    public enum LessonStatus
    {
        Defined,
        Prepared,
        Practiced,
        Recorded
    }

    public enum ReportStatus
    {
        Draft,
        Revising,
        Finished
    }
}
 
C# CODE EXAMPLE created on Friday, July 02, 2010 permalink
How to use a generic dictionary to total enum values
This code example shows how you can use a generic dictionary to add up the total of each kind of item in an enum collection. It is flexible so that if you add an enum value, it automatically is totaled as well. See Dave Fancher's article showing how this approach is actually faster than various approaches with LINQ.
using System;
using System.Collections.Generic;

namespace TestDict2394343
{
    class Program
    {
        static void Main(string[] args)
        {

            List<LessonStatus> lessonStatuses = new List<LessonStatus>();
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Recorded);
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Prepared);
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Prepared);
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Prepared);
            lessonStatuses.Add(LessonStatus.Defined);

            Section section = new Section(lessonStatuses);
            section.ShowTotals();
            Console.ReadLine();

        }


        public class Section
        {
            protected Dictionary<string, int> _lessonStatusTotals = new Dictionary<string, int>();

            public Section(List<LessonStatus> lessonStatuses)
            {
                foreach (var lessonStatus in Enum.GetNames(typeof(LessonStatus)))
                {
                    _lessonStatusTotals.Add(lessonStatus, 0);
                }


                foreach (var lessonStatus in lessonStatuses)
                {
                    _lessonStatusTotals[lessonStatus.ToString()]++;
                }
            }

            public void ShowTotals()
            {
                foreach (KeyValuePair<string, int> lst in _lessonStatusTotals)
                {
                    Console.WriteLine("{0}: {1}", lst.Key, lst.Value);
                }
            }
        }

        public enum LessonStatus
        {
            Defined,
            Prepared,
            Practiced,
            Recorded
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, July 06, 2010 permalink
How to stop regular expression greediness
This example shows how you can tell a regular expression to only get the text before the first colon, thanks Matthew and Jason.
using System;
using System.Text.RegularExpressions;

namespace TestRegex92343
{
    class Program
    {
        static void Main(string[] args)
        {

            //Regex regex = new Regex(@"(?<label>.+):s*(?<text>.+)"); //wont' work in second case

            {
                string line = "title: The Way We Were";
                Regex regex = new Regex(@"(?<label>[^:]+):s*(?<text>.+)");
                Match match = regex.Match(line);
                Console.WriteLine("LABEL IS: {0}", match.Groups["label"]);
                Console.WriteLine("TEXT IS: {0}", match.Groups["text"]);
            }

            {
                string line = "title: The Way We Were: A Study of Youth";
                Regex regex = new Regex(@"(?<label>[^:]+):s*(?<text>.+)");
                Match match = regex.Match(line);
                Console.WriteLine("LABEL IS: {0}", match.Groups["label"]);
                Console.WriteLine("TEXT IS: {0}", match.Groups["text"]);
            }

            Console.ReadLine();

        }
    }
}

 
C# CODE EXAMPLE created on Sunday, August 22, 2010 permalink
How to use a Dictionary<> with struct key to save a dynamic matrix of objects
The following is an example of how you can save both a fixed matrix of objects and a dynamic matrix of objects (size determined at runtime) using first a multi-dimensional array and then a generic dictionary with a struct key. In both examples you can pick the object out of the map with the x/y coordinates.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;

namespace TestDoubarray
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            StaticMatrixExampleWithArray();
            DynamicMatrixExampleWithDictionary(10, 10);
            DynamicMatrixExampleWithDictionary(20, 20);
        }

        private void StaticMatrixExampleWithArray()
        {

            CheckBox[,] checkBoxes = new CheckBox[10, 10];

            for (int x = 0; x < 10; x++)
            {
                for (int y = 0; y < 10; y++)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = String.Format("x={0}/y={1}", x, y);
                    checkBoxes[x,y] = cb;
                }
            }

            CheckBox cbOut = checkBoxes[4, 8];
            Message.Text += cbOut.Tag.ToString() + Environment.NewLine;
        }

        private void DynamicMatrixExampleWithDictionary(int xMax, int yMax)
        {
            Dictionary<MatrixCoordinates, CheckBox> checkboxes = new Dictionary<MatrixCoordinates, CheckBox>();

            for (int x = 0; x < xMax; x++)
            {
                for (int y = 0; y < yMax; y++)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = String.Format("x={0}/y={1}", x, y);
                    checkboxes.Add(new MatrixCoordinates { X = x, Y = y }, cb);
                }
            }

            CheckBox cbOut = checkboxes[new MatrixCoordinates { X = 4, Y = 8 }];
            Message.Text += cbOut.Tag.ToString() + Environment.NewLine;
        }

        private struct MatrixCoordinates
        {
            public int X { get; set; }
            public int Y { get; set; }
        }
    }
}
 
C# CODE EXAMPLE created on Thursday, September 02, 2010 permalink
Extension method for checking regex in one line
This simple extension method allows you to check strings against regular expressions in one line.
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace TestRegex2342343
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> texts = new List<string>()
            {
                "233-2887",
                "2332887",
                "442-1121",
                "",
                null
            };

            foreach (var text in texts)
            {
                if (text.MatchesRegex("^[0-9]{3}-[0-9]{4}$"))
                    Console.WriteLine(text + " matches");
                else
                    Console.WriteLine(text + " does NOT match");
            }
            Console.ReadLine();
        }
    }

    public static class Helpers
    {
        public static bool MatchesRegex(this string text, string regex)
        {
            if (text == null || regex == null)
                return false;
            else
            {
                Match match = Regex.Match(text, regex);
                return match.Success;
            }
        }
    }
}
 
C# CODE EXAMPLE created on Tuesday, September 07, 2010 permalink
A simple class that represents a matching quiz item
This is a class that encapsulates matching items which can be displayed as a test with questions and answers and then shows the answer key.
using System.Collections.Generic;
using System;
using System.Threading;

namespace TestSort727272
{
    class Program
    {
        static void Main(string[] args)
        {
            MatchingItems matchingItems = new MatchingItems();
            matchingItems.Add("one", "111");
            matchingItems.Add("two", "222");
            matchingItems.Add("three", "333");
            matchingItems.Add("four", "444");
            matchingItems.Setup();

            matchingItems.DisplayTest();
            matchingItems.DisplayAnswers();

            Console.ReadLine();

        }
    }

    public class MatchingItems
    {
        public List<MatchingItem> Collection { get; set; }
        public List<int> LeftDisplayIndexes { get; set; }
        public List<int> RightDisplayIndexes { get; set; }

        private char[] _numbers = { '1', '2', '3', '4', '5', '6', '7', '8' };
        private char[] _letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

        public MatchingItems()
        {
            Collection = new List<MatchingItem>();
            LeftDisplayIndexes = new List<int>();
            RightDisplayIndexes = new List<int>();
        }

        public void Add(string leftText, string rightText)
        {
            MatchingItem matchingItem = new MatchingItem(leftText, rightText);
            Collection.Add(matchingItem);
            LeftDisplayIndexes.Add(Collection.Count - 1);
            RightDisplayIndexes.Add(Collection.Count - 1);
        }

        public void DisplayTest()
        {
            Console.WriteLine("");
            Console.WriteLine("--TEST:-------------------------");
            for (int i = 0; i < Collection.Count; i++)
            {
                int leftIndex = LeftDisplayIndexes[i];
                int rightIndex = RightDisplayIndexes[i];
                Console.WriteLine("{0}. {1,-12}{2}. {3}", _numbers[i], Collection[leftIndex].LeftText, _letters[i], Collection[rightIndex].RightText);
            }
        }
        public void DisplayAnswers()
        {
            Console.WriteLine("");
            Console.WriteLine("--ANSWERS:-------------------------");
            for (int i = 0; i < Collection.Count; i++)
            {
                string leftLabel = _numbers[i].ToString();
                int leftIndex = LeftDisplayIndexes[i];
                int rightIndex = RightDisplayIndexes.IndexOf(leftIndex);
                string answerLabel = _letters[rightIndex].ToString();

                Console.WriteLine("{0}. {1}", leftLabel, answerLabel);

            }
        }

        public void Setup()
        {
            do
            {
                LeftDisplayIndexes.Shuffle();
                Thread.Sleep(300);
                RightDisplayIndexes.Shuffle();
            } while (SomeLinesAreMatched());
        }

        private bool SomeLinesAreMatched()
        {
            for (int i = 0; i < LeftDisplayIndexes.Count; i++)
            {
                int leftIndex = LeftDisplayIndexes[i];
                int rightIndex = RightDisplayIndexes[i];
                if (leftIndex == rightIndex)
                    return true;
            }
            return false;
        }


        public void DisplayAsAnswer(int numberedIndex)
        {
            Console.WriteLine("");
            Console.WriteLine("--ANSWER TO {0}:-------------------------", _numbers[numberedIndex]);
            for (int i = 0; i < Collection.Count; i++)
            {
                int leftIndex = LeftDisplayIndexes[i];
                int rightIndex = RightDisplayIndexes[i];

                Console.WriteLine("{0}. {1,-12}{2}. {3}", _numbers[i], Collection[leftIndex].LeftText, _letters[i], Collection[rightIndex].RightText);
            }
        }
    }

    public class MatchingItem
    {
        public string LeftText { get; set; }
        public string RightText { get; set; }

        public MatchingItem(string leftText, string rightText)
        {
            LeftText = leftText;
            RightText = rightText;
        }
    }

    public static class Helpers
    {                
        static Random rng = new Random();
        public static void Shuffle<T>(this IList<T> list)
        {
            int n = list.Count;
            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    }

}

 
C# CODE EXAMPLE created on Tuesday, September 07, 2010 permalink
Extension method to sort a generic collection of objects
This example shows a method which randomizes any generic collection you give it. It is based on the Fisher Yates shuffle.
using System.Collections.Generic;
using System;

namespace TestSort727272
{
    class Program
    {
        static void Main(string[] args)
        {
            List<MatchingItem> matchingItems = new List<MatchingItem>();

            matchingItems.Add(new MatchingItem("one", "111"));
            matchingItems.Add(new MatchingItem("two", "222"));
            matchingItems.Add(new MatchingItem("three", "333"));
            matchingItems.Add(new MatchingItem("four", "444"));

            MatchingItem.Display(matchingItems);
            matchingItems.Shuffle();
            MatchingItem.Display(matchingItems);
            matchingItems.Shuffle();
            MatchingItem.Display(matchingItems);

            Console.ReadLine();

        }
    }

    public class MatchingItem
    {
        public string LeftText { get; set; }
        public string RightText { get; set; }

        public MatchingItem(string leftText, string rightText)
        {
            LeftText = leftText;
            RightText = rightText;
        }

        public void Display()
        {
            Console.WriteLine(LeftText + " / " + RightText);
        }

        public static List<MatchingItem> ResortIntoRandomOrder(List<MatchingItem> matchingItems)
        {
            List<MatchingItem> newOrderItems = new List<MatchingItem>();
            //...matchingItems.Sort();
            return newOrderItems;
        }

        public static void Display(List<MatchingItem> matchingItems)
        {
            Console.WriteLine("");
            Console.WriteLine("--DISPLAY:-------------------------");
            foreach (var matchingItem in matchingItems)
            {
                matchingItem.Display();
            }
        }
    }

    public static class Helpers
    {
        static Random rng = new Random();
        public static void Shuffle<T>(this IList<T> list)
        {
            int n = list.Count;
            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    }
}
 
C# NOTES ON ARTICLE created on Wednesday, March 11, 2009 permalink
Notes On Article: MSDN: Lambda Expressions
Kept running into Lambda syntax that I didn't fully understand so took some time and read the MSDN article on lambdas to get the syntax and concepts down.
  1. this is the original syntax that was confusing:
    this.regionManager.RegisterViewWithRegion(RegionNames.MainRegion,
                                                            () => this.container.Resolve<EmployeesPresenter>().View);
  2. with a little experimenting, got this to work, interesting but need some real examples:
    using System;

    namespace TestLambda
    {
        delegate int Simple(int i);
        delegate string Simple2(string str);
        delegate void Simple3();

        class Program
        {

            static void Main(string[] args)
            {
                Simple squareIt = x => x * x;
                int j = squareIt(5);
                Console.WriteLine("j = {0}", j);

                Simple2 addSuffix = x => x + " (this is added to the end of the string)";
                string message = addSuffix("This is a sentence.");
                Console.WriteLine(message);

                Simple3 showMessage = () => { Console.WriteLine("this is a test"); };
                showMessage();

                Console.ReadLine();

            }

        }

    }

  3. the above results in:
  4. A lambda expression is the most convenient way to create that delegate.
  5. You could do it with Func but it is more difficult syntax.
  6. All restrictions that apply to anonymous methods also apply to lambda expressions.
  7. Here is a code example I made with anonymous methods.
  8. This makes sense with my original example above: (input parameters) => expression.
  9. If you are creating expression trees that will be consumed in another domain, such as SQL Server, you should not use method calls in lambda expressions.
  10. Talks about expression lambdas.
  11. statement lambdas: much like an anonymous method it seems.
  12. here is an example of Func:
    using System;

    namespace TestLambda
    {
        class Program
        {
            static void Main(string[] args)
            {
                Func<int, bool> checkIt = x => x == 5;
                bool result4 = checkIt(4);
                bool result5 = checkIt(5);
                Console.WriteLine("Result4 is {0}", result4); //false
                Console.WriteLine("Result5 is {0}", result5); //true

                Console.ReadLine();
            }
        }
    }
  13. also nice, very compact syntax:
    using System;
    using System.Linq;

    namespace TestLambda
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
                int numberOfOddNumbers = numbers.Count(n => n % 2 == 1);

                Console.WriteLine("there are {0} odd numbers", numberOfOddNumbers); // there are 5 odd numbers

                Console.ReadLine();
            }
        }
    }
  14. Ok this is interesting as we are doing what I know as LINQ now, so LINQ and lambdas and anonymous functions all are similar and overlapping.
  15. Also nice: var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);.
  16. The compiler can infer the type based on the lambda body.
  17. Talks about variable scope, e.g. Lambdas can refer to outer variables that are in scope in the enclosing method.
 
C# NOTES ON ARTICLE created on Saturday, April 18, 2009 permalink
Notes On Article: The Beauty of Closures
This article by Jon Skeet shows in code the evolution in C# from predicates (1.0) to anonymous methods (2.0) to lambda expressions (3.0). As a bonus he shows how each concept is expressed in Java and concludes that in terms of closures, C# is more flexible (e.g.    enables the defered execution in LINQ).
  1. This article will talk about C# (versions 1, 2 and 3) and Java (before version 7).
  2. Closures allow you to encapsulate some behaviour, pass it around like any other object, and still have access to the context in which they were first declared.
  3. Shows the code in Java and C# (of different versions) to illustrate different approaches.
  4. Closures are about "hiding that logic away".
  5. VOCABULARY: predicate, n. something which matches or doesn't match a given item
  6. FLASHCARD: In c# what is the natural way of representing a predicate?
  7. Interesting: [h]Predicate<T> and Func<T, bool> are functionally equivalent.[/h], LINQ prefers the later.
  8. In Java there's no such thing as a delegate, so he uses an interface with a single method.
  9. recreates LINQ's Where<> functionality, nice:
        public static class Tools
        {
            public static IList<T> Filter<T>(IList<T> source, Predicate<T> predicate)
            {
                List<T> ret = new List<T>();
                foreach (T item in source)
                {
                    if (predicate(item))
                    {
                        ret.Add(item);
                    }
                }
                return ret;
            }
        }
  10. uses the above method with C# 1 first, then C#2, and C#3, nice:
                List<string> names = new List<string>() { "Jim", "Joe", "Hank", "Alice" };

                //C# 1 (predicates)
                Predicate<string> predicate = new Predicate<string>(MatchStartWithJ);
                IList<string> namesWithJ = Tools.Filter(names, predicate);
                Tools.Dump(namesWithJ);

                //C# 2 (anonymous methods)
                Predicate<string> predicate2 = delegate(string item)
                {
                    return item.StartsWith("J");
                };
                IList<string> namesWithJ2 = Tools.Filter(names, predicate);
                Tools.Dump(namesWithJ2);

                //C# 3 (lambda expressions)
                var filteredNames = Tools.Filter(names, n => n.StartsWith("J"));
                Tools.Dump(filteredNames);
  11. So up to now, the predicate method has needed no local variables, this is where closures come in.
  12. C# 1 doesn't have support for closures, "no simple place to store the piece of information we need".
  13. Shows how you have to use a class in C# 1 to save the local information.
  14. In Java, the value of the variable has been captured by the anonymous class. In C#, the variable itself has been captured by the delegate.
  15. In java, you can't change the value of a captured variable. It has to be final, so the question is moot, the values of captured variables are copied when the predicate is created (it seems though that you could use reference variables to get past this, e.g. not a string but a StringBuilder in Java).
  16. Talks about how you have to keep the above in mind with e.g. Actions.
                List<Action> actions = new List<Action>();
                for (int count = 1; count <= 10; count++)
                {
                    actions.Add(() => Console.WriteLine(count));
                }
                foreach (Action action in actions)
                {
                    action();
                }
                actions.Clear();


                for (int count = 1; count <= 10; count++)
                {
                    int copy = count;
                    actions.Add(() => Console.WriteLine(copy));
                }

                foreach (Action action in actions)
                {
                    action();
                }
  17. "The benefit that closures often bring, however, is composability."
  18. Without closures, you "lose the locality of the logic".
  19. Closures make it simpler to create delegates.
  20. Once you start thinking in terms of delegates, the ways to combine them become obvious.
  21. You could create a Predicate<T> which takes two other predicates, and represents either the logical AND or OR of them.
  22. With the deferred execution and data streaming provided by LINQ to Objects, you incur significantly less memory overhead.
  23. One of the key features of lambda expressions is brevity.
 
C# NOTES ON ARTICLE created on Wednesday, April 22, 2009 permalink
Notes On Article: Why Properties Matter
I posted this question about readonly C# properties and this article was mentioned, more lucid writing on C# by Jon Skeet.
  1. Not talking about whether something should be a method or property.
  2. Topic at hand is: [h]how you expose data: as a property or as a non-private field[/h].
  3. Answer: no fields should ever be non-private (except for fields in nested classes perhaps).
  4. Ok he's going write to the heart of the matter: explains why you shouldn't create public variables and then convert them properties later.
  5. Reason #1: serialization.
  6. Reason #2: you can use a field for ref parameters, whereas you can't (in C# at least) use a property in the same way.
  7. Reason #3: reflection: your code will break if it is expecting a field to be present and it's been turned into a property unexpectedly.
  8. Benefit of using properties #1: you can have a public get and a protected set.
  9. Benefit of using properties #2: you can add breakpoint in a getter/setter.
  10. Benefit of using properties #3: you can log in a getter/setter.
  11. Benefit of using properties #4: properties are used for data binding, fields aren't.
  12. The main point is [h]why not just be consistent to start with, just always use properties, automatic properties of C# 3 make it a no-brainer[/h].
  13. The only exception: if it is a nested type since it is only used internally.
  14. Ok, so I understand from this article that Jon would not even approve of this "public readonly bool IsValid;".