<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>'Adventures in .NET' Blog RSS Feed</title>
    <link>http://www.programmersheaven.com/user/spickersgill/blog/</link>
    <description>Contains the latest posts from the blog 'Adventures in .NET'</description>
    <lastBuildDate>Thu, 09 Feb 2012 07:17:12 -0800</lastBuildDate>
    <generator>Argotic Syndication Framework 2007.3.0.1, http://www.codeplex.com/Argotic</generator>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <item>
      <title>My BLOG has moved</title>
      <link>http://www.programmersheaven.com/user/spickersgill/blog/1101-My-BLOG-has-moved/</link>
      <description>I've moved my BLOG to &lt;a href="http://dotnetadventurer.blogspot.com/"&gt;blogger&lt;/a&gt;.  Please renew any stored links to this new address (&lt;a href="http://dotnetadventurer.blogspot.com/"&gt;http://dotnetadventurer.blogspot.com&lt;/a&gt;)</description>
      <guid isPermaLink="true">http://www.programmersheaven.com/user/spickersgill/blog/1101-My-BLOG-has-moved/</guid>
      <pubDate>Sat, 25 Jul 2009 10:28:34 -0800</pubDate>
      <dc:creator>spickersgill</dc:creator>
    </item>
    <item>
      <title>Debugging Client Side JavaScript using Firebug's Console</title>
      <link>http://www.programmersheaven.com/user/spickersgill/blog/1051-Debugging-Client-Side-JavaScript-using-Firebugs-Console/</link>
      <description>Firefox is among the most useful of tools to web developers.  Not only for viewing web pages you create on an alternative web browser, but also due to the plethora of add-ons available for it.  Foremost among these add-ons is Firebug, a feature that presents a GUI for drilling  through any web page and viewing the CSS, HTML and Script.&lt;br /&gt;
&lt;br /&gt;
[includeimage:1]&lt;br /&gt;
&lt;br /&gt;
Firebug in use...&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;How to get Firebug&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Get Firebug by following these simple steps;&lt;br /&gt;
&lt;br /&gt;
1) In Firefox's menu go to Tools -&amp;gt; Add-ons&lt;br /&gt;
&lt;br /&gt;
2) In the Add-ons dialog click "Get Add-ons" on the toolbar&lt;br /&gt;
&lt;br /&gt;
3) Type "firebug" into the search box&lt;br /&gt;
&lt;br /&gt;
4) Expand Firebug in the results list and click the "Add to Firefox..." button.&lt;br /&gt;
&lt;br /&gt;
NOTE: If Firebug isn't listed when the results appear click on the "See all results" link at the bottom of the results list.  This will take you to the full results listing where you will be able to add the add-on to Firefox.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Using Firebug&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Once Firebug has been installed and Firefox has been restarted you'll notice the Firebug icon has appeared in the bottom right icon tray of Firefox.  Click this icon to open Firebug.  Click the "Inspect" button and move your mouse around the web page you're currently viewing.  You'll notice that a blue rectangle appears to represent each HTML element, such as div, span, table etc in the underlying HTML.  Click to display the details of the underlying HTML within the Firebug UI.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;The Console&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This is a really useful aspect of Firebug that provides an output for you to write to in your client script, and can be used extensively for debugging your client script.&lt;br /&gt;
&lt;br /&gt;
You will need to enable the console for sites you wish to use it on:&lt;br /&gt;
&lt;br /&gt;
[includeimage:2]&lt;br /&gt;
&lt;br /&gt;
Once you've done this, Firebug will expose an object in Firefox simply called "console", which you will then be able to call in your script. You can read the Console documentation at &lt;a href="http://getfirebug.com/console.html"&gt;http://getfirebug.com/console.html&lt;/a&gt;  Pay special attention to the &lt;strong&gt;String Substitution Patterns&lt;/strong&gt; which allow you to output different data types, most notably objects, to the console.&lt;br /&gt;
&lt;br /&gt;
A brief code example should help to explain:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&amp;lt;script language="javascript" type="text/javascript"&amp;gt;
	
        function debug(obj) {
            if (console)
                console.log("%o", obj);
        }

&amp;lt;/script&amp;gt;        
&lt;/pre&gt;&lt;br /&gt;
This function allows your JavaScript code to write an object to the console. The "%o" substitution pattern means that Firebug will interpret the passed parameter as an object, and will represent it in the console as a browsable tree, much the same way that the local window does in Visual Studio.&lt;br /&gt;
&lt;br /&gt;
[includeimage:3]&lt;br /&gt;
&lt;br /&gt;
Apart from the above there are &lt;em&gt;many&lt;/em&gt; other useful methods available on the console object, described in the API documentation (&lt;a href="http://getfirebug.com/console.html"&gt;http://getfirebug.com/console.html&lt;/a&gt;) that will make your JavaScript debugging much, much easier.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;The Script Debugger&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
The Script debugger also needs to be enabled on a site by site basis.  Once enabled the underlying HTML will be displayed in the Script window.  As you scroll through the source you will notice that any embedded script appears with &lt;span style="color: Green;"&gt;green&lt;/span&gt; line numbers.  You can click any green line numbers to place a stop in the code, again very much the way you may be used to in IDE's such as Visual Studio.&lt;br /&gt;
&lt;br /&gt;
[includeimage:4]</description>
      <guid isPermaLink="true">http://www.programmersheaven.com/user/spickersgill/blog/1051-Debugging-Client-Side-JavaScript-using-Firebugs-Console/</guid>
      <pubDate>Wed, 15 Jul 2009 07:37:28 -0800</pubDate>
      <dc:creator>spickersgill</dc:creator>
    </item>
    <item>
      <title>Aspects of Polymorphism in .NET Part 4 - Interfaces</title>
      <link>http://www.programmersheaven.com/user/spickersgill/blog/1024-Aspects-of-Polymorphism-in-NET-Part-4---Interfaces/</link>
      <description>&lt;strong&gt;Part Four: Interfaces&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
If you've read parts 1-3 of this blog you'll be aware that we've used the real world objects, cars, to draw a parallel with, and explain, classes, inheritance and abstraction. I hope that, by this stage, you are beginning to undertand and recognise the advantages that come from properly object orienting your code.  Flexibility for future development is a key aspect of proper OO design.&lt;br /&gt;
Although the code examples in this BLOG have been written in C#, one of the .NET languages, the principles apply to all Object Oriented languages.&lt;br /&gt;
&lt;br /&gt;
So, we now come to &lt;em&gt;Interfaces&lt;/em&gt;.  What role do they have in object oriented programming?&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Contracts&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
I have often read that Interfaces can be likened to contracts.  The thinking behind this analogy is that a class implementing an interface MUST implement ALL of the methods and properties declared by the interface, much the way that an employee MUST carry out all of the responsibilities contained in his contract of employment if he wants to keep his job. However, I don't really find this analogy to be particularly helpful as it doesn't really explain &lt;em&gt;why&lt;/em&gt; you'd bother to create or implement an interface in the first place.  So, I'm going to explain the use of interfaces by extending our hypothetical car model already used throughout this BLOG.  I sincerely hope that this will clarify the use of interfaces for any of you who are a little confused about them.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Recap&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
At the end of part three you should have started to see that by abstracting a "Car" class and implementing that abstract class in our "Focus" class we could then build other classes that made use of &lt;strong&gt;Cars&lt;/strong&gt; (generic and flexible) rather than specific models such as &lt;strong&gt;Focus&lt;/strong&gt; (narrow and restrictive).  An abstract class was ideal for the "Car" because it allowed us to implement logic that was common to all cars within the abstract class, and declare abstract methods for logic that would &lt;strong&gt;have&lt;/strong&gt; to be implemented by sub classes.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Manual or Automatic?&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In the UK (where I'm from) 90% of the cars on the road are manual transmission with the vast minority being automatic. Drivers who take their driving test in an automatic car are restricted to only being able to drive automatic cars.  On the other hand, those who pass their test in a manual car can drive either manual or automatic.  Modelling this behaviour in our example case is an ideal environment for &lt;strong&gt;interfaces&lt;/strong&gt;.&lt;br /&gt;
&lt;br /&gt;
Although it's not compulsory, it is common practice to precede the name an interfaces with a capital "I".  So, let's create interfaces that define manual and automatic cars.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
    public interface IManual
    {
        bool ClutchDepressed
        {
            get;
            set;
        }

        void ShiftUp(int gearFrom, int gearTo);

        void ShiftDown(int gearFrom, int gearTo);
    }

    public interface IAutomatic
    {
        void ShiftDrive();

        void ShiftReverse();

        void ShiftPark();
    }
&lt;/pre&gt;&lt;br /&gt;
You will notice that our interfaces contain no implementation (i.e. logic that says &lt;em&gt;how&lt;/em&gt; to do any of the things declared), they simply declare methods and properties that any implementing classes MUST provide logic for.&lt;br /&gt;
&lt;br /&gt;
So, when the hypothetical engineers at Ford build different models of the Focus, they will implement one of these interfaces depending on the kind of transmission they will be using.  Let's go back and update our code in order to implement one of these interfaces.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
    public class FocusAuto : Focus, &lt;span style="color: Blue;"&gt;IAutomatic&lt;/span&gt;
    {
        public FocusAuto(Guid keyCode)
            : base(keyCode) { }

        public FocusAuto(Guid keyCode, int numDoors) : base(keyCode, numDoors) { }


        &lt;span style="color: Blue;"&gt;public void ShiftDrive()
        {
            //... Logic to change the gear into Drive and 
            // then automatically through the gears as the car moves ...
        }

        public void ShiftReverse()
        {
            //... Logic to change the gear into Reverse ...
        }

        public void ShiftPark()
        {
            //... Logic to change the gear into Park ...
        }&lt;/span&gt;

    }
&lt;/pre&gt;&lt;br /&gt;
You'll notice that I've created a new class, called &lt;strong&gt;FocusAuto&lt;/strong&gt;.  This means that we've managed to avoid changing our existing &lt;strong&gt;Focus&lt;/strong&gt; class.  Focus, still implements &lt;strong&gt;Car&lt;/strong&gt;, so we still benefit from all of the logic contained in &lt;strong&gt;Focus&lt;/strong&gt; and &lt;strong&gt;Car&lt;/strong&gt;.  However, as highlighted in &lt;span style="color: Blue;"&gt;blue&lt;/span&gt;, the new &lt;strong&gt;FocusAuto&lt;/strong&gt; class implements the &lt;strong&gt;IAutomatic&lt;/strong&gt; interface.  As a result it MUST implement the three methods declared by the interface.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;The Benefits&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Why put this definition in an interface?  After all, the &lt;strong&gt;FocusAuto&lt;/strong&gt; class could easily have contained the logic without implementing the &lt;strong&gt;IAutomatic&lt;/strong&gt; interface.  Simply remove the &lt;strong&gt;, IAutomatic&lt;/strong&gt; from the class definition and the code will still compile...&lt;br /&gt;
&lt;br /&gt;
The reason is simple and yet very powerful - and remarkably similar to the benefits we derived from abstracting logic into a &lt;strong&gt;Car&lt;/strong&gt; class...&lt;br /&gt;
&lt;br /&gt;
Earlier I mentioned that interfaces are often likened to contracts.  Think about what contracts do... For example, your employment contract defines what is expected of you as an employee.  However, it also serves as a marker or identifier for YOU.  If you have a contract that defines the role of a C# developer that is what you &lt;em&gt;are&lt;/em&gt;.&lt;br /&gt;
&lt;br /&gt;
Interfaces do the same for classes - they act as identifiers for what the class &lt;em&gt;is&lt;/em&gt;, or &lt;em&gt;does&lt;/em&gt;. So, we can now diffentiate drivers based on what they are allowed to drive.  Let's create a new class to demonstrate this&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
    public class AutomaticDriver
    {
        private Car myCar;

        public IAutomatic MyCar
        {
            get
            {
                return (IAutomatic)myCar;
            }
            set
            {
                myCar = (Car)value;
            }
        }

        public void Init()
        {
            Guid _keyCode = new Guid();
            if (myCar != null)
            {
                myCar.Start(_keyCode);
                myCar.Accelerate(0, 50);
                myCar.Brake();
            }
        }        
    }
&lt;/pre&gt;&lt;br /&gt;
Because our AutomaticDriver class doesn't really care about &lt;em&gt;who&lt;/em&gt; made the Automatic car it drives all it has to do is check that the car &lt;strong&gt;is&lt;/strong&gt; an automatic.  Therefore &lt;em&gt;any&lt;/em&gt; car that implements the IAutomatic interface will be allowable.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
            FocusAuto myAuto = new FocusAuto(new Guid());
            AutomaticDriver driver = new AutomaticDriver();
            driver.MyCar = myAuto;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Summary&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Throughout this BLOG on polymorphism you have seen that there is much to be gained by OO design - designing at the interface level rather than the object level.  In fact, this is the basic premise of Design Patterns (recommended for further reading).&lt;br /&gt;
&lt;br /&gt;
I have used a real world parallel in order to convey these concepts because I often find it easier to understand new concepts by looking for every day instances around me.  I hope you have found this series to be helpful and insightful.</description>
      <guid isPermaLink="true">http://www.programmersheaven.com/user/spickersgill/blog/1024-Aspects-of-Polymorphism-in-NET-Part-4---Interfaces/</guid>
      <pubDate>Wed, 08 Jul 2009 06:30:46 -0800</pubDate>
      <dc:creator>spickersgill</dc:creator>
    </item>
    <item>
      <title>Aspects of Polymorphism in .NET Part 3 - Abstract Classes</title>
      <link>http://www.programmersheaven.com/user/spickersgill/blog/1000-Aspects-of-Polymorphism-in-NET-Part-3---Abstract-Classes/</link>
      <description>&lt;strong&gt;Part Three: Abstraction&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
All of us are aware of abstract concepts, although perhaps we aren't &lt;em&gt;aware&lt;/em&gt; that we're aware.  To explain... all of us know that there are things we can touch, possess, and things that we can't.  For example, we all eat food, but we never actually have &lt;em&gt;a&lt;/em&gt; food.  Food is an &lt;em&gt;abstract&lt;/em&gt; concept and we actually eat &lt;em&gt;instances&lt;/em&gt; of food - apples, hamburgers, pizzas, carrots, etc.  &lt;br /&gt;
&lt;br /&gt;
Abstraction is at the top level of most things we're familiar with on a day to day basis.  In our Ford Focus illustration we were dealing with a concrete instance of an abstract concept - vehicle.  Although a person may be said to own a vehicle, it's meaningless without specifying the &lt;em&gt;type&lt;/em&gt; of vehicle he or she possesses.  For most of us this is a car, but for some it might be a plane, a boat, a bike, a helicopter etc.  We then further solidify things by becoming more and more specific about things - what make, model, variation of car we have, for example.&lt;br /&gt;
&lt;br /&gt;
In programming terms abstraction allows us to define a very loose model for something without specifying exactly &lt;em&gt;how&lt;/em&gt; the implementation will be handled.  Abstraction comes in varying degrees in the programming world.  There are &lt;strong&gt;Interfaces&lt;/strong&gt;, which are completely abstract (contain absolutlely no implementation code), and  &lt;strong&gt;abstract classes&lt;/strong&gt;, which can contain a mixture of abstract methods and implementation code.  This will all be explained before long, so don't worry if you don't understand these terms just yet.&lt;br /&gt;
&lt;br /&gt;
We'll start by moving one step up the vehicle abstraction hierarchy from our Focus, to the &lt;em&gt;Car&lt;/em&gt; to explain abstract classes.  Cars come in all different shapes and sizes, but all working cars share certain characteristics, no matter how new, old, cheap or expensive they are.  They all start, stop, move, turn etc.  How these characteristics are accomplished though, can be different from one car to the next.  For example, one manufacturer may start the car by a simple key turn, another by a push button, yet another by fingerprint recognition. On the other hand, though, some things are common between all cars - they are all driven by an engine, stopped by brakes etc.  These rules apply for cars, but not for other types of vehice - sailing boats, for example, are driven by the wind and stopped (if in a hurry) by an anchor.&lt;br /&gt;
&lt;br /&gt;
So, if we were to extend our model code for the Focus we would have to say that our Focus is a &lt;strong&gt;concrete&lt;/strong&gt; implementation of a Car (abstract class).  Of course, because we're building our code in the order in which wer're covering the topics in this blog, we'll next be building our abstract "Car" class.  In pratice, we would design our classes using a modelling tool such as UML, designing interfaces and abstractions up front - the inverse to the way wer'e doing things in this blog - and code concrete classes on the basis of our abstractions.  For further reading on the matter Google "Design Patterns" or "Gang of Four".  &lt;br /&gt;
&lt;br /&gt;
There is a lot to be said for abstracting functionailty, but I strongly believe that you need understand the bigger picture first.&lt;br /&gt;
&lt;br /&gt;
Let's have a look at how we code an abstract class in C#:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
namespace Ford
{
    public abstract class Car
    {
        public abstract void Start(Guid keyCode);
    }
}
&lt;/pre&gt;&lt;br /&gt;
This is a very basic start, but it demonstrates all that we need to show for now...  First of all notice the use of the keyword &lt;em&gt;abstract&lt;/em&gt;.  This marks the class as being abstract, so instances of this class cannot be created. So,&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
Car c = new Car();
&lt;/pre&gt;&lt;br /&gt;
will result in a compilation error:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Red;"&gt;Cannot create an instance of the abstract class or interface 'Ford.Car'&lt;/span&gt;
&lt;/pre&gt;&lt;br /&gt;
Next we have an abstract method:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public abstract void Start(Guid keyCode);
&lt;/pre&gt;&lt;br /&gt;
Notice that this method doesn't have a body (i.e. no curly braces).  That's because the method is abstract - its implementation, or &lt;em&gt;how&lt;/em&gt; it will start, &lt;strong&gt;must&lt;/strong&gt; be coded in a class that implements this abstract class.  We'll soon see how this affects the Focus class, which we'll alter to implement the &lt;strong&gt;Car&lt;/strong&gt; class.&lt;br /&gt;
&lt;br /&gt;
However, abstract classes &lt;em&gt;can&lt;/em&gt; contain implementation logic too, which is then inherited by the classes that implement it.  For example, since in our fairly basic example, we can safely assume that all cars will accelerate by engaging the engine and stop by engaging the brakes, we can promote this logic to the abstract class level.  Then &lt;strong&gt;all&lt;/strong&gt; cars will benefit from this standard logic.&lt;br /&gt;
Our modifies abstrat class now looks like this:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
   public abstract class Car
    {
        protected Engine _engine = new Engine();
        private double _currentSpeed;
        private Brake[] _brakes = new Brake[4] { new Brake(), new Brake(), new Brake(), new Brake() };

        public abstract void Start(Guid keyCode);

        public void Accelerate(double initialSpeed, double endSpeed)
        {
            while (_currentSpeed &amp;lt; endSpeed)
            {
                _engine.Throttle();
            }
            _engine.Idle();
        }

        public void Brake()
        {
            _brakes[0].Apply();
            _brakes[1].Apply();
            _brakes[2].Apply();
            _brakes[3].Apply();
        }

    }
&lt;/pre&gt;&lt;br /&gt;
Now we'll look at the changes we need to make to our &lt;em&gt;Focus&lt;/em&gt; class in order to implement the &lt;em&gt;Car&lt;/em&gt; class.  &lt;br /&gt;
&lt;br /&gt;
As a reminder, let's look at the code as it &lt;strong&gt;was&lt;/strong&gt;:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public class Focus{
    private Engine _engine = new Engine();
    private double _currentSpeed;
    private int _doorCount = 4;
    private Guid _keyCode;

    public Focus(Guid keyCode){
	//Default constructor
	_keyCode = keyCode;
    }

    public Focus(Guid keyCode, int numDoors) : this(keyCode)
    {
	_doorCount = numDoors;		
    }

    public void Start(Guid keyCode)
    {        
	if(keyCode == _keyCode)
            _engine.Start();
    }

    public void Accelerate(double initialSpeed, double endSpeed)
    {
	while(_currentSpeed &amp;lt; endSpeed){
	    _engine.Throttle();
            
	}
	_engine.Idle();
    }

    public int DoorCount{
	get{
	    return _doorCount;
	}
	set{
	    _doorCount = value;
	}
    }

    // ...
    // ...

}
&lt;/pre&gt;&lt;br /&gt;
In order to implement the new &lt;em&gt;Car&lt;/em&gt; abstract class the following changes need to be made:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
    public class Focus : Car
    {
        private int _doorCount = 4;
        private Guid _keyCode;

        public Focus(Guid keyCode)
        {
            //Default constructor
            _keyCode = keyCode;
        }

        public Focus(Guid keyCode, int numDoors)
            : this(keyCode)
        {
            _doorCount = numDoors;
        }

        public override void Start(Guid keyCode)
        {
            if (keyCode == _keyCode)
                _engine.Start();
        }

        public int DoorCount
        {
            get
            {
                return _doorCount;
            }
            set
            {
                _doorCount = value;
            }
        }

        // ...
        // ...

    }
&lt;/pre&gt;&lt;br /&gt;
Notice the changes to the class:&lt;br /&gt;
1) We've added &lt;strong&gt;: Car&lt;/strong&gt; to the class declaration.  Just as with the extension of &lt;strong&gt;Focus&lt;/strong&gt; into &lt;strong&gt;FocusLE&lt;/strong&gt;, this notifies the compiler that we are going to be implementing the Car abstract class.&lt;br /&gt;
2) The &lt;strong&gt;Accelerate&lt;/strong&gt; method has been removed since this logic is now contained in the abstract class.&lt;br /&gt;
3) We still have the &lt;strong&gt;Start&lt;/strong&gt; method, although we've had to add the &lt;em&gt;override&lt;/em&gt; keyword to the method statement.&lt;br /&gt;
&lt;br /&gt;
Why do we get rid of &lt;strong&gt;Accelerate&lt;/strong&gt;, but keep &lt;strong&gt;Start&lt;/strong&gt;?  Because Start is declared as an abstract method in the Car class.  In other words it &lt;strong&gt;must&lt;/strong&gt; be implemented in a child class, such as "Focus".  On the other hand, &lt;strong&gt;Accelerate&lt;/strong&gt; contains implementation logic within the abstract "Car" class and therefore doesn't need to be overriden in the "Focus" class - although it &lt;em&gt;could be&lt;/em&gt; if needed.&lt;br /&gt;
&lt;br /&gt;
Now, when we create an instance of &lt;strong&gt;Focus&lt;/strong&gt; we get access to the &lt;strong&gt;Accelerate&lt;/strong&gt; and &lt;strong&gt;Brake&lt;/strong&gt; methods.  Let's create a new class, called "Driver" and demonstrate this inheritance:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
    public class Driver
    {
        public void Init()
        {
            Guid _keyCode = new Guid();
            Focus myFocus = new Focus(_keyCode);
            myFocus.Start(_keyCode);
            &lt;span style="color: Blue;"&gt;myFocus.Accelerate(0, 50);
            myFocus.Brake();&lt;/span&gt;
        }        
    }
&lt;/pre&gt;&lt;br /&gt;
The code highlighted blue demonstrates the fact that the "myFocus" object (i.e. the instance of the "Focus" class) can Accelerate and Brake even though "Focus" doesn't define these methods.  &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Why?&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
You may be wondering - "why is any of this useful?"  Well, now that we've abstracted things out to the level of "Car" we can deal at that abstract level.  Say for example, we were creating a class called "Garage".  We can now easily build that "Garage" class around Cars rather than Focuses.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
    public class Garage
    {
        public void Service(Car aCar)
        {
            //...
            //Code to Service the care
            //...
        }
    }
&lt;/pre&gt;&lt;br /&gt;
Because every "Focus" is also a "Car" (by virtue of the fact that it has implemented the "Car" abstract class) this, and any other class that implements the "Car" abstract class can now be serviced at the "Garage".  &lt;br /&gt;
&lt;br /&gt;
Once you understand the principles of abstraction it doesn't take long to realise the massive potential for it to make your code more flexible and extensible.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Summary&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
This tutorial has demonstrated &lt;em&gt;what&lt;/em&gt; abstract classes are, and by the time you've finished reading this series of blogs on polymorphism I hope you will feel sufficiently equipped to go on to further reading, such as books on Design Patterns.  These books will help you to get a stronger grasp on the far reaching benefits of abstraction.&lt;br /&gt;
&lt;br /&gt;
The next and final part of this blog series will deal with interfaces.</description>
      <guid isPermaLink="true">http://www.programmersheaven.com/user/spickersgill/blog/1000-Aspects-of-Polymorphism-in-NET-Part-3---Abstract-Classes/</guid>
      <pubDate>Thu, 25 Jun 2009 07:55:01 -0800</pubDate>
      <dc:creator>spickersgill</dc:creator>
    </item>
    <item>
      <title>Aspects of Polymorphism in .NET Parts 1 &amp; 2 - Inheritance</title>
      <link>http://www.programmersheaven.com/user/spickersgill/blog/963-Aspects-of-Polymorphism-in-NET-Parts-1--2---Inheritance/</link>
      <description>An Introduction to Interfaces, Abstract classes and Inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
.NET Developers come in various shapes and sizes, not only physically, but also in terms of their expertise and experience.  The polymorphic nature of the .NET Framework now allows their code to benefit from similar diversity.&lt;br /&gt;
Sadly, though, it is entirely possible with .NET languages and tools, such as Visual Studio 2008, for developers to build programs and web sites without necessarily needing to know or understand the underlying complexity of what they are doing.  I've come across so-called developers whose approach to solving problems has greatly improved their search engine skills as they scour the internet for code samples they can lift to fix the problem they're currently facing.  Sadly, though, their attitude towards actually understanding and getting to grips with the problem domain is one of laziness.&lt;br /&gt;
For this reason developers can work commercially, producing viable code and making extensive use of the vast array of controls and tools at their disposal, yet not fully understand such basic lower level concepts as abstraction, inheritance and polymorphism.  To be fair, though, this is quite understandable.  After all, much of the documentation available on these topics is far from light reading, and tends to go to much greater depth than is necessary for the average beginner wanting to gain a basic understanding.  This blog will therefore provide an easier access into these areas of object oriented (OO) programming techniques.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Part One: Object Orientation - What's all the Fuss?&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
I first came into .NET languages after years of developing solely in Visual Basic.  Newer developers, who have only really got into the programming game since the inception of the .NET Frameworks will no doubt be a little confused by this statement.  To explain... Visual Basic existed as a much more simple language prior to VB.NET.  A VB developer was largely looked down upon by other members of the programming community (Java, Delphi, C++ etc) because Visual Basic was, rightly, viewed as an inferior language.  Why?  Because it masked a lot of complexity from the developers using it.  Inheritance wasn't even an option.&lt;br /&gt;
During this period I started learning a little Java and had my first exposure to proper OO programming.  At about the same time the first version of the .NET Framework was seeing the light of day, and my movement into C# from Java was therefore very organic.&lt;br /&gt;
So, what's all the fuss about?  Well, Object Oriented programming allows a much more flexible and extensible approach to developing your code than you would otherwise have.  Let's explain by means of a real world parallel, as I often find these to be the best aids.&lt;br /&gt;
&lt;br /&gt;
If you drive, you no doubt, unless you're very wealthy (in which case, why are you reading this blog?), own a car built on a production line by one of the world's major car manufacturers.  Your car started its life on a production line along with a load of other cars just like yours.  Let's say, for example, that you drive a Ford Focus.  Although your Focus is identical in shape and size to all other Focuses manufactured at the same time as yours, it isn't necessarily identical in all areas.  Ford offers a diverse range of trim levels across the Focus range that affects such items as wheels, tyres, engine size, fuel type, leather or cloth seats etc.&lt;br /&gt;
However, although you may have requested a certain level of individuality for your car, Ford didn't have to send their designers back to the drawing board in order to build your car.  They stuck with the basic design of the Focus and simply changed peripherals.&lt;br /&gt;
This is a real world instance of what Object Oriented programming techniques allow.  A programmer can develop a class that does everything he or she wants it to.  However, unless he seals the class, which prevents it from being extended (although Method Extensions in .NET Framework 3.5 can provide a workaround for developers wishing to extend sealed classes) another developer can extend or override aspects of the class so that it fits their own individual needs.  This is called polymorphism (poly meaning "many" and "morph" meaning shape).  When you stop to think about it you'll soon realise the potential benefits you can reap from this.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Part Two: Inheritance&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
If we were to draw a parallel to the above example in the programming world, engineers at Ford would have built what's called a base class and named it something like "Focus".  This class would define and implement various properties and methods.  For example:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public class Focus{
    private Engine _engine = new Engine();
    private double _currentSpeed;
    private int _doorCount = 4;
    private Guid _keyCode;

    public Focus(Guid keyCode){
	//Default constructor
	_keyCode = keyCode;
    }

    public Focus(Guid keyCode, int numDoors) : this(keyCode)
    {
	_doorCount = numDoors;		
    }

    public void Start(Guid keyCode)
    {        
	if(keyCode == _keyCode)
            _engine.Start();
    }

    public void Accelerate(double initialSpeed, double endSpeed)
    {
	while(_currentSpeed &amp;lt; endSpeed){
	    _engine.Throttle();
            
	}
	_engine.Idle();
    }

    public int DoorCount{
	get{
	    return _doorCount;
	}
	set{
	    _doorCount = value;
	}
    }

    // ...
    // ...

}
&lt;/pre&gt;&lt;br /&gt;
Now, let's say they decide to release a limited edition Focus that has a push button start, instead of a traditional key turn.  One safety condition is that the clutch has to be depressed before the engine can be started.  Several other novel features are added, but for the sake of simplicity this is the one we'll focus on (no pun intended).&lt;br /&gt;
Since the code for the base class is pretty much as it needs to be, the engineers can use inheritance to extend the existing functionality.  They therefore create a new object called "FocusLE" (LE = Limited Edition).&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public class FocusLE : Focus{
    
}
&lt;/pre&gt;&lt;br /&gt;
By using the ":" operator the compiler is told that this new class inherits from the "Focus" base class.  The new class inherits all of base class' public and protected methods and properties.  However, we now want to create a new Start() method that takes an additional parameter:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public class FocusLE : Focus{
    public void Start(Guid keyCode, bool clutchDepressed){
	if(clutchDepressed)
	    base.Start(keyCode);
    }
}
&lt;/pre&gt;&lt;br /&gt;
Because the new class inherits from the "Focus" base class the new Start() method can invoke the Start() method in the base class by use of the &lt;strong&gt;base&lt;/strong&gt; keyword once it has done its check to make sure that the clutch is depressed.  However, we don't want to leave the old Start() method publically exposed.  So we have to do what's called &lt;em&gt;hiding&lt;/em&gt; the base class' method.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public class FocusLE : Focus{
    public void Start(Guid keyCode, bool clutchDepressed){
	if(clutchDepressed)
	    base.Start(keyCode);
    }

    //override the StartMethod in the base class
    public new void Start(Guid keyCode){
	//Do nothing	
    }
}
&lt;/pre&gt;&lt;br /&gt;
Because the engineers who created the the base "Focus" class didn't anticipate a later revision with a different start mechanism they didn't declare the base class' Start() method using the &lt;strong&gt;virtual&lt;/strong&gt; keyword.  That's why we use the &lt;strong&gt;new&lt;/strong&gt; keyword when declaring the hiding method.  We &lt;em&gt;could&lt;/em&gt; leave it out but the compiler would issue a warning. This hiding Start() method means that trying to start the new "FocusLE" without providing the second parameter will do nothing.  If we hadn't hidden this method of the base class in our new class the old Start() method would still have been available and we would have had a potential safety risk.&lt;br /&gt;
&lt;br /&gt;
Had the original engineers looked ahead and declared the original Start method with the &lt;strong&gt;virtual&lt;/strong&gt; keyword we would have been able to override this in the "FocusLE" class.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
public class FocusLE : Focus{
    public void Start(Guid keyCode, bool clutchDepressed){
	if(clutchDepressed)
	    base.Start(keyCode);
    }

    //override the StartMethod in the base class
    public override void Start(Guid keyCode){
	//Do nothing	
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Part Three: Abstraction&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In part three of this blog I will expand our example to explain the idea of abstraction in object oriented programming.  Part Four will look at Interfaces and what they're useful for.</description>
      <guid isPermaLink="true">http://www.programmersheaven.com/user/spickersgill/blog/963-Aspects-of-Polymorphism-in-NET-Parts-1--2---Inheritance/</guid>
      <pubDate>Tue, 09 Jun 2009 09:21:12 -0800</pubDate>
      <dc:creator>spickersgill</dc:creator>
    </item>
    <item>
      <title>Delegates Explained in Plain English</title>
      <link>http://www.programmersheaven.com/user/spickersgill/blog/956-Delegates-Explained-in-Plain-English/</link>
      <description>Delegates are fundamental to the .NET Framework (events and callbacks wouldn't work without them) and can be &lt;em&gt;extremely &lt;/em&gt;powerful to the .NET Developer once they come to grasps with exactly &lt;em&gt;what &lt;/em&gt;they are and &lt;em&gt;how &lt;/em&gt;to use them.  In this blog I will consider aspects of a real world situation in which delagates are useful, after which I will explain, in illustrative terms exactly what delegates are all about.  You will see how delegates are an intrinsic part of the &lt;strong&gt;events&lt;/strong&gt; structure in the .NET framework, but also why they are useful in their own right.  First, though, we need to understand a little about the origins of delgates in the .NET framework.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;The origins of delegates&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Delegates in .NET languages such as C# and VB.NET are akin to function pointers in C++.  I have found that simply being aware of this pseudonym it extremely helpful in understanding delegates. The term helps us to understand that delegates allow a developer to provide a pointer to a method/function/sub etc.  But when would a developer find this to be useful?  &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Where delegates are needed&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Let's say, for example, that you are developing a Windows Forms application and you want to open a new instance of a form.  You want your new form to do some work and update its opener at some point down the line.  &lt;br /&gt;
&lt;br /&gt;
To expand, let's take a real world example.  I developed a Windows Forms application in C# that was used for managing staff and contracts within a cleaning business. This was an MDI application and had toolbars on the MDI parent form with lists of staff and contracts so that the user could easily select a member of staff or a contract to work on.  When the user selected a member of staff or contract a new form was opened.  There was also, as you would expect, forms for creating new staff members and new contracts.  These forms needed to update the main form whenever a new member of staff or a new contract was added to the system so that the main form could refresh its lists.  In a basic application you might accomplish this by opening these forms modally directly from the main form and then updating the lists when the new staff form closes.  Something along the lines of:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Green;"&gt;//... MainForm code ...&lt;/span&gt;
NewStaffForm _nuForm = new NewStaffForm();
_nuForm.ShowDialog();

&lt;span style="color: Green;"&gt;//Assume that the user clicked the OK button on the
//NewStaffForm and added a new member of staff&lt;/span&gt;

RefreshStaffList();
&lt;/pre&gt;&lt;br /&gt;
However, this is extremely limiting.  The &lt;span style="color: Blue;"&gt;ShowDialog()&lt;/span&gt; method for opening the &lt;span style="color: Blue;"&gt;NewStaffForm &lt;/span&gt;form holds execution of the subsequent code within the &lt;span style="color: Blue;"&gt;MainForm &lt;/span&gt;until the &lt;span style="color: Blue;"&gt;NewStaffForm &lt;/span&gt;has closed. &lt;br /&gt;
&lt;br /&gt;
What if you want your application to be more flexible than that and keep your &lt;span style="color: Blue;"&gt;MainForm &lt;/span&gt;useable while the &lt;span style="color: Blue;"&gt;NewStaffForm &lt;/span&gt;is in use?  What if you want your &lt;span style="color: Blue;"&gt;NewStaffForm &lt;/span&gt;to do more than just notify your &lt;span style="color: Blue;"&gt;MainForm &lt;/span&gt;that it's created a new user?  Say, for example, you want it to pass information back to the &lt;span style="color: Blue;"&gt;MainForm&lt;/span&gt;?  This is where delegates come in.&lt;br /&gt;
&lt;br /&gt;
In particular, in this instance, an &lt;strong&gt;event &lt;/strong&gt;would be useful; but as you will see, in .NET delegates are inseparable from events.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Revising our code to use delegates and events&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
No doubt you're very familiar with &lt;em&gt;events&lt;/em&gt; and have made extensive use of events belonging to other objects.  However, until you actually create your own events you probably don't really know or care what's going on.  So, let's revise our code and explain what we're doing at each stage.&lt;br /&gt;
&lt;br /&gt;
First, we want to declare an event handler in our code.  It doesn't really matter where this event handler is declared so long as it has public scope so that it can be seen by other objects.  A delegate can be declared &lt;em&gt;outside&lt;/em&gt; of a class declaration, as it is essentially a type declaration, just as a class is.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;public delegate void NewStaffCreatedHandler&lt;/span&gt;(&lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt; NewStaffMember)
&lt;/pre&gt;&lt;br /&gt;
Notice that this event handler is actually a &lt;strong&gt;delegate&lt;/strong&gt;.  Also, notice that it takes a parameter of type &lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt;.  This is a custom type specific to this program.  It's details are not relevant to this blog, so I'll go no further in describing it.&lt;br /&gt;
&lt;br /&gt;
Next, we declare an event in our &lt;span style="color: Blue;"&gt;NewStaffForm&lt;/span&gt;.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;&lt;span style="color: Blue;"&gt;public event&lt;/span&gt; &lt;span style="color: Green;"&gt;NewStaffCreatedHandler &lt;/span&gt;NewStaffCreated;&lt;/pre&gt;&lt;br /&gt;
Notice that the event has, as its type, the event handler we just declared.  &lt;br /&gt;
&lt;br /&gt;
Next, we write code to raise the event.  This looks very much like a method call:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;&lt;span style="color: Blue;"&gt;protected void&lt;/span&gt; CreateNewStaffMember()
{
    &lt;span style="color: Blue;"&gt;StaffMember &lt;/span&gt;_newStaffMember = new &lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt;();
    &lt;span style="color: Green;"&gt;//... Code to create the new StaffMember...&lt;/span&gt;

    &lt;span style="color: Green;"&gt;//Raise the event&lt;/span&gt;
    NewStaffCreated(_newStaffMember);
}&lt;/pre&gt;&lt;br /&gt;
Where exactly is the code that runs when the event is raised? Remember what we said earlier about the origins of delegates lying in C++ function pointers.  As I said, remembering this pseudonym helps to understand what delegates are all about.&lt;br /&gt;
&lt;br /&gt;
When the event is raised we are actually calling the function(s) (or method(s)) that the delegate &lt;em&gt;points&lt;/em&gt; to.  How do we point the delegate to a method?  Well, where events are concerned I'm willing to bet that it's something you already know how to do.  We simply assign a method to the event be doing the following in our &lt;span style="color: Blue;"&gt;MainForm &lt;/span&gt;form.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;&lt;span style="color: Green;"&gt;//Create an instance of the NewStaffForm and assign a method to the NewStaffCreatedHandler&lt;/span&gt;
&lt;span style="color: Blue;"&gt;NewStaffForm &lt;/span&gt;_nuForm = &lt;span style="color: Blue;"&gt;new NewStaffForm&lt;/span&gt;();
_nuForm.NewStaffCreated += &lt;span style="color: Blue;"&gt;new&lt;/span&gt; &lt;span style="color: Green;"&gt;NewStaffCreatedHandler&lt;/span&gt;(NewStaffForm_NewStaffCreated);
_nuForm.Show();
&lt;/pre&gt;&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Green;"&gt;//This is the method that the delegate points to&lt;/span&gt;
&lt;span style="color: Blue;"&gt;void&lt;/span&gt; NewStaffForm_NewStaffCreated(&lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt; NewStaffMember)
{
    RefreshStaffList();

    NewStaffMember.AddedToList = &lt;span style="color: #000000;"&gt;true&lt;/span&gt;; &lt;span style="color: Green;"&gt;//Do something with the StaffMember object that was passed with the delegate&lt;/span&gt;
}
&lt;/pre&gt;&lt;br /&gt;
&lt;strong&gt;Explaining what's happening in Plain English&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;em&gt;Why are delegates called delegates?&lt;/em&gt;&lt;br /&gt;
&lt;br /&gt;
In the real world a delegate is usually a person.  What function do they serve?  Well, imagine a large company wants to have a presence at a conference.  The whole company can't relocate to the conference venue for its duration - that would be impractical.  Rather, the company assigns a delegate (or delegates) to go and represent the company at the conference.  The delegate might be given specific instructions about how he or she is to behave when there, which hotel they are to stay in, what their budget for food &amp;amp; drink is etc, but the delegate, being a human being, has relative freedom besides these constraints.  When the delegate returns from the conference he or she may have to report back to the company about it.&lt;br /&gt;
&lt;br /&gt;
In the .NET framework a delegate fulfils a similar purpose.  Where one class may wants to be represented within another class it can use a delegate.  This is a lot more efficient that passing itself to the other class in its entirety, and is a lot more flexible. The delegate has to conform to certain limitations, though, just as the real world delegate does.&lt;br /&gt;
&lt;br /&gt;
When a delegate is declared it is declared much along the lines of a method/sub/function declaration.  For example, in C#, a delegate declaration might look like:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;public delegate void &lt;/span&gt;&lt;span style="color: Green;"&gt;NewStaffCreatedHandler&lt;/span&gt;(&lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt; NewStaffMember)
&lt;/pre&gt;&lt;br /&gt;
It is given a scope &lt;strong&gt;public&lt;/strong&gt;, a return type &lt;strong&gt;void&lt;/strong&gt; (although it could equally be any other type), and specifies parameters.  This constitutes the agreement as to how the implementation of the delegate (i.e. the method/sub/function it points to) must behave.  In other words, any method/sub/function that this delegate points to &lt;strong&gt;must&lt;/strong&gt; return a void and take a &lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt; object parameter.&lt;br /&gt;
&lt;br /&gt;
The most common event handler delegate &lt;span style="color: Green;"&gt;EventHandler&lt;/span&gt;, for example, has the following declaration:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;public delegate void&lt;/span&gt;&lt;span style="color: Green;"&gt; EventHandler&lt;/span&gt;(&lt;span style="color: Blue;"&gt;object&lt;/span&gt; sender, &lt;span style="color: Blue;"&gt;EventArgs&lt;/span&gt; e);
&lt;/pre&gt;&lt;br /&gt;
All events are of a &lt;strong&gt;delegate&lt;/strong&gt; type.  In other words, all events are declared with a specific delegate as their representative.  For example, a delegate at a Microsoft conference could report back on an event that a delegate at an Sun conference couldn't (although they in turn &lt;em&gt;could&lt;/em&gt; report back on an event that the Microsoft delegate couldn't), because they weren't in attendance at the same conference.&lt;br /&gt;
&lt;br /&gt;
So, if you wanted to declare an event in your program that used the standard EventHandler delegate you would declare it as follows:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;public event&lt;/span&gt; &lt;span style="color: Green;"&gt;&lt;strong&gt;EventHandler&lt;/strong&gt;&lt;/span&gt; MyEvent;
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Delegates aren't restricted to events&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Although we've used &lt;strong&gt;events&lt;/strong&gt; as a springboard for our explanation of &lt;strong&gt;delegates&lt;/strong&gt;, there's no reason to limit delegates to this useage.  In the MDI application I mentioned above I didn't actually use events at all (although, as can be seen, I could easily have).  I knew that I wanted my child forms to update my parent forms by means of a function call.  This created the environment for the use of a delegate, but to save on the the extra declaration of an event in my child form I simply declared a constructor for my child forms that took my &lt;strong&gt;delegate&lt;/strong&gt; as a parameter.  For exeample:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;public delegate void&lt;/span&gt; &lt;span style="color: Green;"&gt;NewStaffCreatedDelegate&lt;/span&gt;(&lt;span style="color: Blue;"&gt;StaffMember 
NewStaffMember&lt;/span&gt;);

&lt;span style="color: Blue;"&gt;public class&lt;/span&gt; NewStaffForm : &lt;span style="color: Green;"&gt;Form&lt;/span&gt;{
    &lt;span style="color: Blue;"&gt;public&lt;/span&gt; NewStaffForm (&lt;span style="color: Green;"&gt;NewStaffCreatedDelegate&lt;/span&gt; callbackDelegate){
        &lt;span style="color: Green;"&gt;//Constructor logic&lt;/span&gt;
    }
}
&lt;/pre&gt;&lt;br /&gt;
Then, when I wanted to callback to my parent form I simply invoked the delegate:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
callbackDelegate(newStaffMember);
&lt;/pre&gt;&lt;br /&gt;
Passing a delegate to the constructor of the child form is very easy.  Simply pass the name of the method that you want the delegate to point to.  For example:&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;NewStaffForm&lt;/span&gt; myChildForm = &lt;span style="color: Blue;"&gt;new&lt;/span&gt; &lt;span style="color: Green;"&gt;NewStaffForm&lt;/span&gt;(myCallBackMethod);
&lt;/pre&gt;&lt;br /&gt;
Don't forget, though, that the method being passed &lt;strong&gt;MUST&lt;/strong&gt; agree to the rules set out for the delegate.  So, it's signature must be the same as that of the delegate.&lt;br /&gt;
&lt;pre class="sourcecode"&gt;
&lt;span style="color: Blue;"&gt;void &lt;/span&gt;myCallBackMethod(&lt;span style="color: Blue;"&gt;StaffMember&lt;/span&gt; newStaffMember){
   &lt;span style="color: Green;"&gt;//Implementation logic&lt;/span&gt;
}
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Summary&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
In essence, delegates allow one class to invoke code in another class, without necessarily needing to care where that code is, or even if it exists at all...  &lt;br /&gt;
&lt;br /&gt;
Let's go back to the conference scenario to explain.  Microsoft may host a conference and send out invitations to many different partner companies.  At the conference one of their lead developers may provide a sneak preview of a new product.  Delegates in attendance may be given a beta copy to take back with them for trial.  Microsoft doesn't care whether or not all of the companies they invited chose to send a delegate or not.  Their conference won't halt just because one company declined to be represented.&lt;br /&gt;
&lt;br /&gt;
Likewise, one class may expose a property, method parameter or event that allows another class to send a delegate to its code.  The delegate (or more to the point the implementation of the delegate, the method/sub/function that the delegate points to) will have to conform to the delegate's signature.  Most classes that send a delegate may choose to provide an implementation (i.e. logic for the method/sub/function) but some may not.  The inviting class doesn't really care... it will still do what it does and make use of the delegate.  For example, all TextBox control's expose a KeyPress event, but not every form that uses a TextBox control will choose to provide an implementation for the KeyPress handler.  The TextBox control will still work, it's just that nothing will happen when a user presses a key within it - because no implementation of the delegate has been provided by the form.&lt;br /&gt;
&lt;br /&gt;
In conclusion, as you will see from the above, once you understand what delegates are for, and what they enable, you will likely start to realise many different scenarios in which you can use them.  I strongly believe that you can't really claim to be a .NET developer without understanding this fundamental part of the framework.  If you've struggled to understand delegates in the past, or even if you've never really cared much about them before, I hope this blog will help to clarify matters and help you to become a better programmer.</description>
      <guid isPermaLink="true">http://www.programmersheaven.com/user/spickersgill/blog/956-Delegates-Explained-in-Plain-English/</guid>
      <pubDate>Fri, 05 Jun 2009 09:38:40 -0800</pubDate>
      <dc:creator>spickersgill</dc:creator>
    </item>
  </channel>
</rss>
