.NET (C#) – format decimal as price – with no culture specific information and two decimal points

This is one of those where there’s so many ways of doing something simple – you end up going “will someone please just tell me how the…” etc etc :0)
The below is a simple basic way, which ignores all culture specific information (you add the currency symbol yourself), and gives you two decimal points.

		decimal decimalValue = 12.99M;
		string test = String.Format("Item costs £{0:N} only", decimalValue);
		//"Item costs £12.99 only"
		//This will also round correctly - e.g. 12.995 to "13.00", and 12.994 to "12.99".

And if you need to inject the currency symbol based on some logic:

		string currencySymbol = "£";
		string test = String.Format("Item costs {0}{1:N} only", currencySymbol, decimalValue);
		//"Item costs £12.99 only"

And then of course finally we stick this into an extension method:

	public static class ExtDecimal
	{
		public static string ToMoney(this Decimal d, string currencySymbol)
		{
			return String.Format("{0}{1:N}", currencySymbol, d);
		}
	}

	...

	string test = decimalValue.ToMoney("£");
	//"£12.99" - and above example:
	test = String.Format("Item costs {0} only", decimalValue.ToMoney("£"));
	//"Item costs £12.99 only"

Application Timers (to replace scheduled tasks)

I do not like scheduled tasks.
They most often take the form of little bits of unversioned code (in console apps) that exist outside the main solution.
Moving these into the main application allows us to utilise the application’s logging utilities, adds versioning to the logic and configuration settings and ensures that the code is both updated and deployed along with the rest of the solution.

Below is some initial code – the idea is to have a singleton class that starts a set of timers. This can then be called from Application_Start or a similar global event.
Some improvements to the below would be to make the application timers use the provider pattern – so we can code up new timers when we need, and perhaps add a .config section to load these from.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
using System.Net;
using HobNobClubServices.Library;
 
namespace HobNobClubApps.Library
{
      /// 
      /// Singleton timer
      /// 
      public sealed class ApplicationTimers
      {
            private static readonly ApplicationTimers instance = new ApplicationTimers();
            private static bool timersInitialised = false;
 
            private ApplicationTimers() { }
 
            public static ApplicationTimers Instance
            {
                  get
                  {
                        return instance;
                  }
            }
 
            public void InitTimers()
            {
                  if (timersInitialised)
                        return;
 
                  InitHobNobInsuranceEmailAbandonedQuotesTimer();
 
                  timersInitialised = true;//Only do this once in the application:
            }
 
            private void InitHobNobInsuranceEmailAbandonedQuotesTimer()
            {                
                  Timer HobNobInsuranceEmailAbandonedQuotesTimer = new Timer();
                  int intervalInMinutes = Properties.Settings.Default.HobNobInsuranceEmailAbandonedQuotesTimerInterval;
                  HobNobInsuranceEmailAbandonedQuotesTimer.Interval = (intervalInMinutes * 60000); //Convert to millisecs
                  HobNobInsuranceEmailAbandonedQuotesTimer.Elapsed += new ElapsedEventHandler(HobNobInsuranceEmailAbandonedQuotesTimer_Elapsed);
                  HobNobInsuranceEmailAbandonedQuotesTimer.Start();
            }
 
            private void HobNobInsuranceEmailAbandonedQuotesTimer_Elapsed(object sender, ElapsedEventArgs e)
            {
                  string errorMsg = String.Empty;
                  try
                  {
                        int intervalInMinutes = Properties.Settings.Default.HobNobInsuranceEmailAbandonedQuotesTimerInterval;
                        //Set the delay in emailing people to the same as this timer interval (so if this timer runs every 30 mins, people will be emailed if they've left a quote alone for 30 mins):
                        string methodNameAndParams = String.Format("/EmailAbandonedQuickQuotes?delayInMinutes={0}", intervalInMinutes);
                        WebRequest webRequest = HttpWebRequest.Create(Properties.Settings.Default.HobNobClubApps_SLHobNobInsurance_HobNobInsurance + methodNameAndParams);
                        WebResponse webResponse = webRequest.GetResponse();                    
                  }
                  catch (Exception ex)
                  {
                        errorMsg = ex.Message;
                        ExceptionManager.LogExceptionEvent(ex, Logger.Source.HobNobInsurance);
                  }
 
                  Logger.WriteInfoLog(
                        String.Format("The HobNobInsuranceEmailAbandonedQuotesTimer ran at {0} {1}",
                                                DateTime.Now, String.IsNullOrEmpty(errorMsg) ? "with no errors (from the timer)." : "and failed with: " + errorMsg),
                              Logger.Source.HobNobInsurance);
            }
      }
}
 

Save time with AutoMapper

Recently did a load of view model classes which were basically flattened or otherwise simplified versions of an underlying DAL project which served up EntitySet objects – with all the heavy change tracking logic and navigation properties that involves.

Half ways through this, RSI was setting in, and I was getting really (really) bored of writing code like this.CustomerId = customer.CustomerId; – and when you get bored, you start making mistakes – and… well it was starting to look like a very long afternoon, let’s leave it at that.

So – I remembered someone once talking about AutoMapper being an excellent free tool for managing this kind of logic. So headed over to http://automapper.codeplex.com/ and downloaded the project – and after some very simple configuration steps I was able to map entire objects in one line of code.
AutoMapper at the most basic “out of the box” level will simply map properties on their name.
For me it worked really well to AutoMap most of the properties -and for anything more advanced, I would simply name the target property differently and do whatever custom mapping logic was required manually.
If you don’t have this level of flexibility – or if you just want to get more involved there is a vast amount of configuration options for you to look into.

Quick overview of steps to setup in an ASP.NET (MVC) application:

Add a static method to configure AutoMapper:

	public class InitAutoMapper
	{
		public static void Configure()
		{
			Mapper.CreateMap<Category, CategoryModel>();
			Mapper.CreateMap<CategoryModel, Category>(); //Two way binding
			....etc

Configure AutoMapper on application start (Global.asax):

	protected void Application_Start(object sender, EventArgs e)
	{
		InitAutoMapper.Configure();
	}

Start using – in this example an overloaded constructor is doing the mapping:

	public class CategoryModel
	{
		public CategoryModel(Category category)
		{
			AutoMapper.Mapper.Map(category, this); //(source, destination) - will map all properties where names match
		}
	}

Multiple Left Joins in Linq to SQL

Had some fun with this – rubbish formatting below – but paste into Visual Studio and autoformat it (ctrl+e+d).

I’ll write some details on this later – but the basic principle is that if you have a nullable foreign key – i.e. you are not sure if you have matches at the end of your table relation and you would normally do a SQL LEFT JOIN, what you need to do in Linq is use the into clause to declare a collection for the results of your join – the reason being that you can then use the DefaultIfEmpty() method in a subsequent from clause to return empty objects where there is no match.
Couple of examples below – first creates a anonymous object on the fly – here you have to null check to set values. The second example beforehand declares a little helper class with Nullable id’s – which gets you round the null checking.
Note that the below uses multiple from clauses to handle the mutiple left join quires (so basically we select from each declared sub-collection).

from p in Persons
    join l in Languages on p.PrimaryLanguageId equals l.Id into tempResult
    join jt in JobTitles on p.JobTitleId equals jt.Id into anotherTempResult    
    from tr in tempResult.DefaultIfEmpty()
    from atr in anotherTempResult.DefaultIfEmpty()    
    orderby p.Id
    where p.Deleted == null
    select new {
        PersonId = p.Id,
        LanguageId = tr == null ? new Nullable() : tr.Id,
        LanguageName = tr.Name,    
        JobTitleId = atr == null ? new Nullable() : atr.Id,
        JobTitleName = atr.Name
    }    

And a more extensive example:

        ///
        /// Person Grid Helper.
        ///
        ///
        /// Linq joins would normally create an anonymous type
        /// – however we cannot use anon types as the grid collection is passed to another method when searching (LoadPersonForSearch).
        ///
        private class PersonGridHelper
        {    
            public int Id { get; set; }
            public string GivenName { get; set; }
            public string FamilyName { get; set; }
            public string OfficeLocation { get; set; }
            public Nullable OfficeLocationId { get; set; }
            public string JobTitle { get; set; }
            public Nullable JobTitleId { get; set; }
            public string Email { get; set; }
            public string EmailDomain { get; set; }
            public int EmailDomainId { get; set; }
            public string AlternateEmail { get; set; }
            public string Mobile { get; set; }
            public string Telephone { get; set; }
            public string Fax { get; set; }
            public string CVFile { get; set; }
            public string ProfilePictureFile { get; set; }
            public string PrimaryLanguage { get; set; }
            public Nullable PrimaryLanguageId { get; set; }
        }

        ///
        /// Loads the main browse grid.
        ///
        public override void LoadGrid()
        {
            IQueryable coll = from person in this.CurrentDataContext.Persons
                                                 join officelocation in this.CurrentDataContext.OfficeLocations
                                                    on person.OfficeLocationId equals officelocation.Id
                                                join jobtitle in this.CurrentDataContext.JobTitles
                                                    on person.JobTitleId equals jobtitle.Id into jobtitles //Nullable FK => left join, DefaultIfEmpty() below
                                                join language in this.CurrentDataContext.Languages
                                                    on person.PrimaryLanguageId equals language.Id into languages //Nullable FK => left join, DefaultIfEmpty() below
                                                join firmemaildomain in this.CurrentDataContext.FirmEmailDomains
                                                    on person.EmailDomainId equals firmemaildomain.Id
                                                from jobtitle in jobtitles.DefaultIfEmpty() //Left join, records from jobtitles collection, if missing default constructor is called
                                                from language in languages.DefaultIfEmpty() //Left join, records from jobtitles collection, if missing default constructor is called
                                                orderby person.FamilyName
                                                where person.Deleted == null
                                                select new PersonGridHelper()
                                                 {
                                                        Id = person.Id
                                                    ,    GivenName = person.GivenName
                                                    ,    FamilyName = person.FamilyName
                                                    ,    OfficeLocation = officelocation.Name
                                                    ,    OfficeLocationId = person.OfficeLocationId
                                                    ,    JobTitle = jobtitle.Name
                                                    ,    JobTitleId = person.JobTitleId
                                                    ,    Email = person.Email
                                                    ,    PrimaryLanguage = language.Name
                                                    ,    PrimaryLanguageId = person.PrimaryLanguageId
                                                    ,    EmailDomain = firmemaildomain.Domain
                                                    ,    EmailDomainId = person.EmailDomainId
                                                 };
                                                 ………………

.NET Collections and Generics in C#

This post is based on Chapter 10 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” available from Apress.

Right – yet another wondrous adventure with Mr. Troelsen awaits us, this time he will explain just what collections and generics can do for us. As always, this is a brief outline, if you really want to know, and be a better developer – we highly recommend getting hold of Mr. Troelsen’s book! It is quite simply very good, bordering on superb.

Collections

So collections are tools for containing objects. An array is the most simple container, but as you will know this has some serious limitations for adding, removing and resizing. So, to the rescue comes the Systems.Collections namespace. Troelsen gives us an outline of the interfaces in here:

System.Collections Interface Meaning in Life
ICollection Defines general characteristics (e.g., size, enumeration, thread safety) for all nongeneric collection types.
IComparer Allows two objects to be compared.
IDictionary Allows a nongeneric collection object to represent its contents using name/value pairs.
IDictionaryEnumerator Enumerates the contents of a type supporting IDictionary.
IEnumerable Returns the IEnumerator interface for a given object.
IEnumerator Enables foreach style iteration of subtypes.
IHashCodeProvider Returns the hash code for the implementing type using a customized hash algorithm.
IList Provides behavior to add, remove, and index items in a list of objects. Also, this interface defines members to determine whether the implementing collection type is read-only and/or a fixed-size container.

Also, we should know that these are organised as follows:

ScreenShot004

So, what we can see is that the ICollection is the most basic interface, and also we have a lot of enumeration going on (see our previous post on this).
Let’s look at all this in some more detail:

ICollection is described in the table above. The IDictionary uses name/value pairs of object type to organise objects, so you could for example store objects of any type (the value) and retrieve these by an ID or string Key – or indeed another object. The IDictionaryIterator simply returns a strongly typed iterator with a Entry property of type DictionaryEntry for each value that is retrieved (so you get stuff like Key/Value – both of type object.
The IList gives you add/remove and index functionality.

So what classes implement these indexes? Troelsen gives us this table:

System.Collections Class Meaning in Life Key Implemented Interfaces
ArrayList Represents a dynamically sized array of objects. IListICollectionIEnumerable, and ICloneable
Hashtable Represents a collection of objects identified by a numerical key. Custom types stored in a Hashtable should always override System. Object.GetHashCode(). IDictionaryICollectionIEnumerable, andICloneable
Queue Represents a standard first-in, first-out (FIFO) queue. ICollectionICloneable, and IEnumerable
SortedList Like a dictionary; however, the elements can also be accessed by ordinal position (e.g., index). IDictionaryICollectionIEnumerable, andICloneable
Stack A last-in, first-out (LIFO) queue providing push and pop (and peek) functionality. ICollectionICloneable, and IEnumerable

So Troelsen wisely recommends that we focus on the interfaces that are implemented here to gain an understanding of what each class brings to the table. Also, he quickly outlines three core classes, ArrayList, Queue and Stack – and leaves the rest to the 3.5 documentation.

You might have noticed that ArrayList is the only in the above table that implements IList. So we’ve kind of already covered this.

The Queue type is a bit more interesting, this basically works on a first-in-first-out basis, much like shopping in your local corner store. So you got Enqueue() and  Dequeue() methods, both handling objects. You can call Peek() to access the next object without popping this off the queue. Note though that you cannot use this to null check – use Count > 0 in stead.

And finally the Stack class is of course a last-in-first-out container, much like the company you work in. If you’re still working that is of course, if not, you probably did not enjoy that attempt at humour.  So this works much like the Queue class, except we now have Push() and Pop() methods. Count and Peek() still works the same way.

Finally note that we have a load of additional collections in the System.Collections.Specialized namespace. A quick overview from Mr. Troelsens most excellent book:

Member of System.Collections.Specialized Meaning in Life
BitVector32 A simple structure that stores Boolean values and small integers in 32 bits of memory.
CollectionsUtil Creates collections that ignore the case in strings.
HybridDictionary Implements IDictionary by using a ListDictionary while the collection is small, and then switching to a Hashtable when the collection gets large.
ListDictionary Implements IDictionary using a singly linked list. Recommended for collections that typically contain ten items or fewer.
NameValueCollection Represents a sorted collection of associated String keys and String values that can be accessed either with the key or with the index.
StringCollection Represents a collection of strings.
StringDictionary Implements a hashtable with the key strongly typed to be a string rather than an object.
StringEnumerator Supports a simple iteration over a StringCollection.

The Trouble With Boxing and Typed Collections

So, next up we’ll be moving onto Generics, but to understand the point of all this, first we must understand the problem of not using generics – that is, the problem of using the System.Object base class to treat all object in a consistent way (because although it sounds good, it’s really not).

So, what is boxing? Well, boxing is a process that allows you to convert a value type to a reference type, on-the-fly so to speak. And this happens a lot more than you think.
Unboxing is of course the opposite, so we have a reference type and we convert it back into a value type, an example I think:

			//A value type
			int x = 24;
			//Box it into an object (reference type)
			object objX = x;
			//Unbox it back into a value type
			int anotherX = (int)objX;

So, why does this happen more often than I think? – you might well ask. Well, working with collections of objects is the answer, another example we think again:

			ArrayList myListOfObjects = new ArrayList();
			//The Arraylist Add() method expects an object, so here we're boxing each one of these ints:
			myListOfObjects.Add(10);
			myListOfObjects.Add(20);
			myListOfObjects.Add(30);
			myListOfObjects.Add(40);
			//Now we want them back as ints:
			for (int i = 0; i < myListOfObjects.Count; i++)
			{
				 //...so we have to unbox each one:
				Console.WriteLine(((int)myListOfObjects[i]));
			}

As you see, this process relies heavily on boxing and unboxing, and why is that a problem? Well two things:

Firstly we obviously have a type safety issue, we are casting objects back into a set type, and any exceptions from this are not known until runtime. In the above simple example this is not a problem, but in complex systems dealing with many different value types, this is a very real concern.

Secondly there is a serious performance issue – the steps involved in boxing and unboxing are:

  1. Allocate a new object on the heap.
  2. Copy the value of the stack based value type into this object.
  3. When unboxing we have to copy the value of the heap object back into a new stack variable.
  4. Finally we end up with a load of objects lying around in the heap waiting for the garbage collector.

Again the above example would never cause any issues, but imagine you have a list with several thousand objects and you start to see the problem.

So what’s the solution? Well for a long time Typed Collections was the best solutions around. I won’t go into much detail on these (because they are not the answer my friends!) Basically you create a custom collection type for each specific type that you need to deal with. So for instance you might have a OrderCollection and a ProductCollection. The basic idea is that you wrap an ArrayList with strongly typed access methods. However, this only solves the type safety issue – but at the same time it also saddles us with a very labour intensive process and a likely maintenance nightmare. Furthermore, as these are nothing but wrappers around more general collection types, we still encounter the same boxing/unboxing issues.
So not much of a solution at all. Who will save me you ask? Generics will save you, that’s who.

Generics to The Rescue

Yes, indeed we are in need of rescuing, so let’s send in the proverbial cavalry.

So in a nutshell generic collections (System.Collections.Generic) allows you to create typed collections on-the-fly (i.e. specify the type at the point of creation) and at also removes the need for boxing and unboxing value types.

How so? Well magic really – or not. Basically we have a List<T> (T is used by convention, for type) which defines a load of operations that are common for typed collections, and collections generally. In our code we supply something like List<Orders> = new List<Orders>(); – and the compiler then replaces the T with Orders and viola! We have a typed collection – which we can create and use in a generic way.
What great fun.

So, other stuff we can do is to create our own generic methods – but you probably won’t really need to so we’ll skip over that bit. Also note that if you have a generic method that takes parameters, you can optionally leave out the type in the <> and rely on the compiler to do some type inference – which you could probably have some fun with using polymorphism.

Further more you can also create generic classes, again I’ll skip over that a bit lightly as it’s really quite specialised. However note that the default keyword is overloaded and when used in generics this can be used to set a generic parameter to it’s default value. So for instance an int would be zero etc etc.

Finally following along with this line of possibilities, you can of course also create a Custom Generic Collection – and once again you are quite unlikely to do this and it almost defies the whole point of generics. Like normal typed collections this is nothing but a wrapper around a generic List<T> collection.
One advantage to be gained is that you would be able to add your own specialised add/insert/remove methods – so thinking about it this might not be completely away with the fairies, but nevertheless I will leave the details out of this.

One interesting aspect of custom generic classes is the use of the where keyword, like this:

		// MyGenericClass derives from Object, while
		// contained items must be a class implementing IDrawable
		// and support a default ctor.
		public class MyGenericClass<T> where T : class, IDrawable, new()
		{...}

This is obviously interesting from a polymorphic point of view, and you can now do all kinds of operations on this generic collection. The options for the where keyword are:

Generic Constraint Meaning in Life
where T : struct The type parameter <T> must have System.ValueType in its chain of inheritance.
where T : class The type parameter <T> must not have System.ValueType in its chain of inheritance (e.g., <T> must be a reference type).
where T : new() The type parameter <T> must have a default constructor. This is very helpful if your generic type must create an instance of the type parameter, as you cannot assume the format of custom constructors. Note that this constraint must be listed last on a multiconstrained type.
where T :NameOfBaseClass The type parameter <T> must be derived from the class specified by NameOfBaseClass.
where T :NameOfInterface The type parameter <T> must implement the interface specified by NameOfInterface. Multiple interfaces can be separated as a comma-delimited list.

A very useful feature.

Generic Inheritance

Finally – finally, note that you can also inherit from generic classes and collections (you may define virtual and abstract methods as well), and also that you can indeed create generic interfaces and implement these.

Some well known .NET interfaces (IEnumerable, IClonable and IComparable)

This post is based on chapter 9 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” available from Apress.

Any type that implements IEnumerable can be used by the foreach statement.
You have two choices if you want to implement IEnumerable – either maintain a member of type ArrayList (or similar) that already implements IEnumerable, and expose this, or you can roll your own.

To roll your own, you need a method called GetEnumerator() which returns an object of the IEnumerator type – so just to be clear: the IEnumerable interface stipulates that you must return an object of type IEnumerator, from a method called GetEnumerator().
You can start handcrafting this, but really what you do is use the “yield return” keyword. So for instance you might have an array (which does not support IEnumerable) – and you can simply place a for loop inside the GetEnumerator() and yield each object out.
What yield does is it stores the current locaton, and restarts execution from this point next time the method is called – which is exactly what an iterator is.

IClonable objects are able to return an identical copy of themselves via the Clone() method. Note that best practise is to return a deep copy of the object (i.e. a new object with the exact same state) as opposed to a shallow copy (a copy of the reference, pointing to the same object on the heap).
Note that the object type has a method MemberwiseClone that can be used for this eaxact purpose – note that if yuu have a type containing only value types you can use this for a deep copy – however if your type has any reference types, you must create a new object to obtain a proper deep copied clone.

IComparable objects are indeed comparable. Wonders never cease. This is most often used in things like Array.Sort(array) calls. To implement this, you need to supply a CompareTo(object obj) method, which should return an int.
Less than zero indicates your object is before the object passed in,  Zero means it’s equal and larger than zero it’s after.
So you can do what you like here, compare strings, Ids, dates – whatever makes sense for your object, just return a signed integer value. However do note that all the types I just mentioned (strings, ints and dates) all implement IComparable so make sure you simply pass the call through where possible (i.e. don’t start writing convuluted if/else staments to compare to ints).

Note that you can build custom comparers (say if you wanted more than one way to compare a given object) by creating a class that implements the IComparer interface. You must then supply a method that has a Compare(obj a, obj b) method. So you could perhaps have two of these for say a Product class – on to compare SKU and one to compare the name.
A neat (and recommended) way of doing this, is to create these IComparer implementations, and then expose them through the Product class. So you get something like this:

		public class Product
		{
			//Use C# 2008 auto-implemented properties:
			public int SKU { get; set; }
			public string Name { get; set; }

			public static IComparer SortBySKU
			{
				get { return (IComparer)new ProductSKUComparer(); }
			}

			public static IComparer SortByName
			{
				get { return (IComparer)new ProductNameComparer(); }
			}
		}

		public class ProductSKUComparer : IComparer
		{
			public int Compare(object x, object y)
			{
				return ((Product)x).SKU.CompareTo(((Product)y).SKU);
			}
		}

		public class ProductNameComparer : IComparer
		{
			public int Compare(object x, object y)
			{
				return ((Product)x).Name.CompareTo(((Product)y).Name);
			}
		}

		public class TestIt
		{
			public TestIt()
			{
				Product[] products = { new Product(), new Product(), new Product() };
				//Assume we have names and SKU on these products:
				Array.Sort(products, Product.SortBySKU);
				//Or:
				Array.Sort(products, Product.SortByName);
			}
		}

OOP: Interfaces in C#

This post is based on Chapter 9 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” available from Apress.

The main purpose of interfaces is to enable us to build types (i.e. classes) that support multiple behaviours. On a more general note they are also at the heart of many OO Design Patterns as they allow you to program to an interface in stead of an implementation – we will return to what that means later on, but just know that if you really want to do OO design, classic inheritance is only the most basic step, and interfaces are a crucial tool for moving on from here.

So, what is an interface? Well an interface defines a behaviour that a class may choose to implement (indeed the java syntax uses “implements” for this, where as C# uses the : also used for inheritance). You can only inherit from one class in the .NET family of languages (see http://en.wikipedia.org/wiki/Multiple_inheritance for some issues around multiple inheritance), but you can implement as many interfaces as you like.

So what is the difference between abstract classes and interfaces, and when should you use what? Well for one thing interfaces have absolutely no implementation – they are simply a description of a behaviour – it’s the implementing class’ job to… implement the actual behaviour, in whatever way it see fit. So I might have two interfaces which defines the following:

	public interface IEnjoyBeer
	{
		void DrinkABeer();
	}

	public interface IActLikeADrunkenLoon
	{
		void DanceOnTheTableInYourPants();
		void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout();
	}

Now we can then define a class that chooses to implement both these – and hence must supply an implementation of all the defined members:

	public class DrunkAsASkunk : IEnjoyBeer, IActLikeADrunkenLoon
	{
		public void DrinkABeer() { Console.WriteLine("Drinking a beer"); }

		public void DanceOnTheTableInYourPants() { Console.WriteLine("Dancing on table in pants!"); }

		public void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout() { Console.WriteLine("Arguing Passionately"); }
	}

In contrast to this, we could do the same with an abstract base class, but we would have to roll both behaviours into one class (no multipl. inherit), which will give you a hint of the limitations of classic inheritance. Note also that we use the virtual method in the base class here to provide a default implementation for drinking a beer:

	public abstract class DrinkLotsOfBeerAndActLikeADrunkenLoon
	{
		public virtual void DrinkABeer() { Console.WriteLine("Drinking a beer"); }
		public abstract void DanceOnTheTableInYourPants();
		public abstract void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout();
	}

	public class DrunkAsSkunk2 : DrinkLotsOfBeerAndActLikeADrunkenLoon
	{
		public override void DanceOnTheTableInYourPants() { Console.WriteLine("Dancing on table in pants!"); }

		public override void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout() { Console.WriteLine("Arguing Passionately"); }
	}

What great examples – no idea how this came to me… Anyways – let’s discuss some aspects of the two examples.

In the last example we have an abstract type that drinks beer and acts like a loon – which doesn’t really ring true, I see an endless number of these types being instantiated across town every weekend, so already we have a hint of a design flaw here. Another good question would be “what about people who enjoy beer without acting like drunken loons?” Or indeed people who act like drunken loons for other reasons than enjoying beer…

In contrast to this, let’s look at the first example using interfaces. So first off the IEnjoyBeer interface makes sense as a separate behaviour – because enjoying beer does not necessarily entail acting like a drunken loon – but, of course for some types it does, but the point is: you have the option to implement either one or both behaviours! You could also have a type that acted like a drunken loon but did not enjoy beer.  Either way – having options is important!

Note also that interfaces are available across class hierarchies – so where inheritance has this fairly rigid tree-like structure, interfaces on the other hand can be plugged in anywhere and at any level.

That is not an exhaustive discussion of interfaces – and we will return to these later when we look at the Strategy pattern in the up and coming OO Design Patterns series – but for now do note that we are not saying that you should use interfaces in stead of inheritance, the two actually compliment each other – we will cover this later, but what you should do is remove variable behaviour from your inheritance structure and instead place this in interfaces. The next step from this will then be moving the implementation of the behaviour (i.e. the interface) out of the specific class, and keep these in reusable classes whose sole purpose is to represent a behaviour. So we will have a more generic interface called IEnjoyADrink – and then a class EnjoyBeer that implements this – and then finally we would design a class called perhaps Person or FridayNightLoon who would implement a IEnjoyADrink implementation of it’s choice – anyways, we’ll return to this… keep reading!

Finally – don’t ever forget to use the Visual Studio Class Diagram tool – this is your new best friend in the world of OOP, just open a new diagram and drop in the types you want to see:

ScreenShot002