Archive for February 2009

Avoid calling a virtual or abstract method from a constructor in C#…especially in VB!

Whenever I’m teaching our intermediate .NET development course, I mention to my students the pitfalls of calling a virtual method from a base class’ constructor.  The major drawback of calling a virtual method in such a context is that if a derived class overrides that method, the overridden method will be invoked prior to the derived class’ instance constructor.  This is especially true in C#, and as you’ll see later in this post, it’s even more dangerous to do so in Visual Basic.

The Marker class

For this demonstration, I will be using a custom Marker class that will simply output text in the console.

This is the Marker class in C# (the class is equivalent in the Visual Basic module):

class Marker
{
    public Marker(string text)
    {
        Console.WriteLine(text);
    }
}

The Base class

Let’s kick off the idea with a single C# class (no inheritance whatsoever):

class Base
{
    private static Marker staticField = new Marker("base static field");
    private Marker instanceField = new Marker("base instance field");

    static Base()
    {
        new Marker("base static ctor");
    }

    public Base()
    {
        M();
        new Marker("base instance ctor");
    }

    protected  virtual void M()
    {
        Console.WriteLine( "base M() was called" );
    }
}

Here’s the same class in Visual Basic:

Class Base

    Private Shared staticField As New Marker("base static field")
    Private instanceField As New Marker("base instance field")

    Shared Sub New()
        Dim temp As New Marker("base static ctor")
    End Sub

    Public Sub New()
        M()
        Dim temp As New Marker("base instance ctor")
    End Sub

    Protected Overridable Sub M()
        Console.WriteLine("base M() was called")
    End Sub

End Class

When we instantiate the Base class, we get the following output in C# and Visual Basic.  The main point is that the results are the same whether we instantiate the C# or Visual Basic version of the Base class.

image

image

 

Instantiating a child class of Base in C# and Visual Basic

Here’s now the entire code in C# of the Base class (same as before) and a Derived class inheriting from it:

class Base
{
    private static Marker staticField = new Marker("base static field");
    private Marker instanceField = new Marker("base instance field");

    static Base()
    {
        new Marker("base static ctor");
    }

    public Base()
    {
        M();
        new Marker("base instance ctor");
    }

    protected  virtual void M()
    {
        Console.WriteLine( "base M() was called" );
    }
}

class Derived : Base
{
    private static Marker staticField = new Marker("derived static field");
    private Marker instanceField = new Marker("derived instance field");

    static Derived()
    {
        new Marker("derived static ctor");
    }

    public Derived()
    {
        new Marker("derived instance ctor");
    }

    protected override void M()
    {
        Console.WriteLine( "derived M() was called" );
    }
}

And here are the same classes in Visual Basic:

Class Base

    Private Shared staticField As New Marker("base static field")
    Private instanceField As New Marker("base instance field")

    Shared Sub New()
        Dim temp As New Marker("base static ctor")
    End Sub

    Public Sub New()
        M()
        Dim temp As New Marker("base instance ctor")
    End Sub

    Protected Overridable Sub M()
        Console.WriteLine("base M() was called")
    End Sub

End Class

Class Derived : Inherits Base

    Private Shared staticField As New Marker("derived static field")
    Private instanceField As New Marker("derived instance field")

    Shared Sub New()
        Dim temp As New Marker("derived static ctor")
    End Sub

    Sub New()
        Dim temp As New Marker("derived instance ctor")
    End Sub

    Protected Overrides Sub M()
        Console.WriteLine("derived M() was called")
    End Sub

End Class

Here’s the output generated when instantiating the Derived class in C# and Visual Basic (This is where the fun begins!  Try to notice any difference between the C# and Visual Basic execution before continuing.) :

image

image

As you can see, the order of execution in an inheritance relationship is both different in C# and Visual Basic (regardless of whether or not a virtual/abstract method was called from either constructor).  The danger of calling a virtual or abstract method from a constructor (in C# or Visual Basic) is that the overridden method will be invoked prior to the derived class’ constructor.  If that method tries to access or modify the state of the yet-to-be-fully-constructed object, you might end up with a corrupt or invalid instance.  The worse scenario is in Visual Basic.  As you can see from the results, the overridden method gets called not only before the derived class’ constructor (as it was with the C# version), but also gets called before the class’ instance fields get initialized.  Now, that’s even more dangerous if the overridden method tries to access any of its instance fields because chances are that they will default to Nothing (null in C#) for reference types since they haven’t even been initialized yet!

Referencing a Visual Basic assembly from a C# application and instantiating the Visual Basic version of the Derived type

Here’s another potential dangerous scenario: From a C# application, you reference a Visual Basic assembly that holds the exact same code as the Base and Derived classes shown above.  You then decide to instantiate the Visual Basic version of the Derived class:

static void Main(string[] args)
{
    Console.WriteLine( "From C# Program" );
    Console.WriteLine(  );
    new VBModule.Derived();
}

Here’s the output generated from instantiating the Visual Basic version of the Derived class in the C# application:

 imageAs you can see, it is no longer having the same execution cycle as when instantiating the C# version of the Derived class from the C# code itself.

Referencing a C# assembly from a Visual Basic application and instantiating the C# version of the Derived type

This time, we’ll switch the roles and from a Visual Basic application, we’ll reference a C# assembly that holds the exact same code as the Base and Derived classes shown above.  We then decide to instantiate the C# version of the Derived class:

Sub Main()
    Console.WriteLine("From VB Program")
    Console.WriteLine()

    Dim d As New CSharp.Derived
End Sub

Here’s the output generated from instantiating the C# version of the Derived class in the Visual Basic application:

imageAs you can see, it is no longer having the same execution cycle as when instantiating the Visual Basic version of the Derived class from the Visual Basic code itself.

Conclusion

You should never be calling a virtual or abstract method from a constructor in C#, and even more in Visual Basic, because in either case a derived type will invoke an instance method prior to the object being fully constructed!  In other words, the dynamic linking edition kicks in as soon as you instantiate a class.  According to Microsoft,

When a virtual method is called, the actual type that executes the method is not selected until run time.  When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed.  The constructor should be redesigned to eliminate the call to the virtual method.

As you saw, the execution cycle is different for both languages even with the same codebase.  It gets even more interesting when referencing either assembly (C# or Visual Basic) in either language, because you just wouldn’t know what you’ll get at the other end.  Having a tool like ReSharper can be of a greater benefit in this circumstance as it’ll catch this kind of code and notify you about it.  By default, this situation will be treated as a warning, but I’ll suggest you to treat it as an error as to make it stand out better (ReSharper->Options…->Inspection Severity):

image

The Fuhrer’s take on Scrum, Agile and CI

I hope you’re not working in this kind of organization.  Period.

The History of Microsoft on Channel9

Recently, the folks over at Channel9 have put on a couple of episodes on the history of Microsoft since its inception.  At the time of this writing, two episodes have been uploaded so far, but we can expect more to be released in the near future.  Each episode is pretty interesting as it also introduces other things that were major at that specific time, such as the unveiling of the Shugart 5.25-inch floppy disk drive for $390.  Ouch.  Anyways, since I wasn’t born in the 1970s, it’s a nice thing to see what was going in the computing industry in that period.

TweetDeck not showing up in primary monitor

I’m currently using TweetDeck v0.21b as my default Tweeter client for my Windows Vista machine.  Having a dual-monitor setup at home (laptop and an external monitor), I always move TweetDeck to the external monitor as a personal preference.  While I’m waiting in the airport for my next flight, the sudden idea to tweet that specific fact came to my mind.  Unfortunately, TweetDeck’s UI doesn’t show up when I launch the application.  I know it’s running because I can see the little black bird icon on the system tray, but it still thinks it’s suppose to show on my external monitor.  That’s not good, because I don’t normally carry my external monitor with me when I’m on the go.  Clearly this is a bug, but not one that will stop me from tweeting the fact that I’m waiting at the airport! 

So these are the steps you should follow if your TweetDeck doesn’t show up in the primary (and only) monitor because it’s thinking it should display on an external monitor:

  1. If you’re using Windows Vista, browse to the following directory: C:\Users\<username>\AppData\Roaming.  If you’re using Windows XP, browse to the following directory instead: C:\Documents and Settings\<username>\AppData.
  2. Locate the folder that begins with TweetDeckFast.  For example, the complete name of that folder on my PC is TweetDeckFast.F9107117265DB7542C1A806C8DB837742CE14C21.1.
  3. Open the Local Store folder.
  4. Edit the preferences_<username>.xml configuration file with your favorite text editor.
  5. Change the windowState XML element’s x attribute to 0.  If you don’t see the TweetDeck UI, it is because the x attribute’s value is negative (which makes sense if the external monitor was on the left side).
  6. Save your changes to that file and load TweetDeck.  You should now be able to see the UI.

The Broken Windows Theory in Software

image I first heard of the Broken Windows theory while reading Malcom Gladwell’s The Tipping Point.  In a nutshell, the theory goes like this:

If a window is broken and left unrepaired, people walking by will conclude that no one cares and no one is in charge.  Soon, more windows will be broken, and the sense of anarchy will spread from the building to the street on which it faces, sending a signal that anything goes.

I couldn’t help myself thinking how this theory fits well with the current state of software development.  When a software project first begins, it is void of any imperfection for no one began to write a single line of code for it.  Then as the team forms and the tasks are being assigned and executed, the team members start to breath life into the software.  That software could have a very different life depending on various factors of the team in charge of developing it, such as the team members’ experience, skills, knowledge, professionalism and passion for the craft. 

From my days of consulting and working as a team member, I more than often see a lack of responsibility from the individual team member for the most important organ of the software: the source code.  Once the source code has started to rot, it doesn’t matter how colorful or beautiful your design documents are or how detailed your development plan is…your software has a cancer and it will die unless you do something about it.  The typical scenario of the Broken Windows theory in software development goes like this: Robert, a programmer, is working on a subroutine for the Shipping module.  While at it, he notices that the NotifySupplier method is lacking a couple of guard clauses and the comments don’t reflect the code at all.  Since he wasn’t the one to write that code, he ignores it and continues working on his work item.  Will he remember to ask the developer who wrote the NotifySupplier method that it is in need of some fixing?  Who knows.  One meeting here, one phone call there, and chances are that Robert will forget about it.  Upon that time, the software has started to confirm the theory.  It now has a broken window.  What’s even more dangerous is that this theory can cascade all over the core of the software if its internals show a high degree of coupling with many components.  A good analogy would be like a tree burning in a forest.  It doesn’t take much time for the fire to spread to the other trees.  The outcome of this is simple: chaos.  The remedy is also simple: you.  What are you going to do about it?  Are you going to run from it or are you going to take corrective actions to prevent the cancer to spread all over the system?

Another potential risky situation that may arise from the Broken Window theory in software development is that if you don’t take care of fixing the broken code as soon as humanly possible, your junior developers and interns (if you have any) will have the impression that all this is normal in our industry.  The result of this is that as they continue to build and ship software in the future, those junior developers and interns will have shipped products with broken windows in them.  The theory can also backfire on your organization as the developers, sooner or later, realize that the organization isn’t mature enough and might decide to work somewhere else that will provide them the proper environment to appreciate the craft of building software and pay attention to the smallest details.   Here are a few examples of what I consider a broken window in the code and that should get fixed as soon as possible:

  • Missing unit tests
  • Comments out-of-sync with the target code
  • A method, class or module that should be refactored
  • A complex piece of code that could be replaced with a design pattern to better express its intent
  • A broken build
  • Etc.

There are also some solutions to prevent this theory to hinder the software project:

  • Performing code reviews at least once a week
  • Encouraging pair programming, as four eyes are better than two ;)
  • Putting in place automated tools that will break the build when rules are broken (FxCop, NDepend, NCover, etc.)
  • Having the programmer check in her modifications in a private build such that if it succeeds then the modifications are merged to the repository.  Have a look at Team City for it does that very well.
  • Providing intelligent tools to your developers so that they can work more effectively with the codebase.  A tool like ReSharper quickly comes into mind.
  • Instilling an atmosphere that considers quality as the most important instrument to drive the organization to success.

But the tools and processes aren’t the heart of the solution.  What will either make or break the software is the attitude of every single individual affected to the project.  To encourage the growth and maturity of this attitude, developers should educate themselves on the trends of software development.  Developers should constantly thrive to do as much as possible to become more valuable software professionals.  

Though he doesn’t talk about this theory explicitly in his book, Agile Principles, Patterns, and Practices in C#, Robert C. Martin does reflect on the basis of the Broken Windows theory and also does provide a remedy to fight this problem in software.  According to him, and I agree with his statement, it’s all about having an attitude of being professional:

The attitude that agile developers have toward the design of the software is the same attitude that surgeons have toward sterile procedure.  Sterile procedure is what makes surgery possible.  Without it, the risk of infection would be far too high to tolerate.  Agile developers feel the same way about their designs.  The risk of letting even the tiniest bit of rot begin is too high to tolerate.

The design must remain clean.  And since the source code is the most important expression of the design, it too must remain clean.  Professionalism dictates that we, as software developers, cannot tolerate code rot.

Remember: Only YOU can prevent broken windows in your software project from spreading like cancer.  You have access to a grand vast of online resources and tools to help you fix those broken windows before it’s too late.  Do you have the attitude to do as such?

Getting Familiar With Your Basic .NET Delegates

The .NET framework is a complete toolbox of programming constructs that allows a developer to create any kind of software.  You’re practically limited by your imagination and knowledge on the framework.  Such a knowledge can be satisfied by getting more familiar with its interfaces, abstract classes, concrete types, events and delegates.  In this post, I want to concentrate on inviting you to get familiar with some basic and powerful delegates provided by the .NET framework.  The reason of this post is that I often see developers create their own delegates that have the same semantics of the ones provided in the framework mostly because they aren’t aware of them.  Instead of violating the DRY principle of programming, let’s discover and learn about them so that we can avoid reinventing the wheel.

The set of basic delegates that I think .NET developers should be familiar and comfortable using are the generic Action<T>, Comparison<T>, Converter<TInput, TOutput> and Predicate<T> delegates.  I will introduce you to each of these delegates by describing their usage with a simple example so that you can start using them in your codebase where needed.

The Action<T> delegate

In .NET 2.0, the Action delegate, declared in mscorlib.dll, has the following signature:

public delegate void Action<T>(T obj);

When Microsoft released .NET 3.5, four more Action delegates were included in System.Core.dll:

public delegate void Action()
public delegate void Action<T1,T2)(T1 arg1, T2 arg2)
public delegate void Action<T1,T2,T3)(T1 arg1, T2 arg2, T3 arg3)
public delegate void Action<T1,T2,T4)(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Regardless of the different signatures of the Action delegate, its semantic is to encapsulate a method which doesn’t return a value, and which holds a variable number of parameters:

  • If the method is parameterless, you should prefer the Action delegate.
  • If the method accepts one parameter, you should prefer the generic Action<T> delegate.
  • If the method accepts two parameters, you should prefer the generic Action<T1, T2> delegate.
  • If the method accepts three parameters, you should prefer the generic Action<T1, T2, T3> delegate.
  • If the method accepts four parameters, you should prefer the generic Action<T1, T2, T3, T4> delegate.
  • If the method accepts five (or more) parameters, you should prefer reviewing your design ;)

A quick analysis with Reflector on the these delegates show that only the Action<T> delegate is being used by .NET in a couple of places, notably as a parameter for the ForEach method of both the static Array class and the generic List<T> class.  The other locations where this delegate is being used aren’t publicly accessible, so we will restrain ourselves to understanding the use of this delegate with a simple usage with the ForEach method of the generic List<T>.

Suppose we have a collection of toys which we want to iterate to display each of its name on the console.  A possible solution to satisfy this requirement without using the Action<T> delegate could be:

// Create our toys collection
List<Toy> toys = Repository<Toy>.FetchAll(); // Not that important how we get our toys collection here

// Iterate through the collection using a foreach statement and display each toy's name on the console
foreach(var toy in toys)
{
  System.Console.WriteLine(toy.Name);
}

The above solution works and your unit tests should pass.  But does it warrant a check-in to the source code repository?  This code we have written to satisfy the requirement seems to me very imperative, almost like how a robot would think.  I am mixing both the “how” and the “what” in this context.  For instance, I am iterating on the collection with a foreach statement (the “how”) in order to fulfill my intent which is to display the toy’s name on the console (the “what”).  Since my brain is better at processing one information at a time, I rather focus on the intention rather than the implementation.  Maybe we can hold on that check-in and see if there’s a better way to do this.

As a matter of fact, there is.  The generic List<T> class defines an instance method which iterates the collection and performs an action for each of its element via an Action<T> delegate.  The Array class defines the same method but it is added as an extension method on that type.  That being said, if there’s another data structure that implements IEnumerable<T> or IEnumerable which doesn’t have an equivalent of a ForEach method, there’s nothing stopping you from creating one on the type via an extension method.  This is the second solution that satisfy this requirement and which clearly brings out my intention forward because I don’t care how the collection is being iterated or what algorithm is used for the iteration, I’m just concerned of doing something with each of its element in a sequential manner.

// Create our toys collection
List<Toy> toys = Repository<Toy>.FetchAll(); // Not that important how we get our toys collection here

// Display each toy's name in the console (using a lambda expression)
toys.ForEach(toy => System.Console.WriteLine(toy.Name));

// You can also use an anonymous delegate to do the same thing...only with more keyboard typing than is necessary
toys.ForEach( delegate(Toy toy)
              {
                System.Console.WriteLine(toy.Name);
              }
            );

Ignoring the instruction using the anonymous delegate, and instead focusing on the one using the lambda expression, we can clearly see that our intention is much clearer.  On a side note, I will use lambda expression whenever needed for the following examples to keep them shorter.  I just added the anonymous delegate if you weren’t too familiar with lambdas.  As you see by using the lambda expression that I don’t have to use the delegate keyword and I can safely rest on the compiler’s type inference  functionality which are both a time saver.  The bottom line with the Action delegate is that it is there for you to do something (perform an action) on an element.  It is commonly used when some action must be performed on an element during an iteration over a collection, but keep in mind that it doesn’t have to be used just in the context of an iteration over a collection.  The Action delegate is also a powerful move to consider when, for example, a collection doesn’t offer a specific iterator that you’re looking for, such as an EvenNumberIterator.  In this case, for every iterated element, you’ll do something specific if the number is even, such as displaying it on the screen (notice that to use multiple statements with lambdas, those statements should be enclosed within braces):

List<int> numbers = Generator<int>.GenerateSequence( 10 ); // Generate a sequence of 10 random numbers

numbers.ForEach( number =>
                 {
                     // Display the number only if it's even
                     if ( number % 2 == 0 )
                        Console.WriteLine( number );
                 }
               );

Something to keep in mind with all the parameterized Action delegates is that the parameters are passed by value which means that any modification to anyone of them will only be local to the scope of delegate’s body or the method being invoked by the delegate.  In other words, the collection’s items won’t be modified.  The multiple parameterized Action delegates introduced in .NET 3.5 allow you to use them in case you need to do something with either two, three or four parameters (they can all be of the same type if needed).

The Comparison<T> delegate

Introduced in .NET 2.0, the generic Comparison<T> delegate is mostly used for sorting elements within a collection.  It is currently used by the Sort methods of both the Array and generic List<T> classes.  This delegate has the following signature:

public delegate int Comparison<T>(T x, T y)

The nature of the delegate is identical to the IComparer<T>.Compare method in that:

  • if x > y, then a positive value is returned (traditionally that value is 1);
  • if x < y then a negative value is returned (traditionally that value is -1);
  • in the case where both x and y are equal, a value of 0 is returned.

This shouldn’t be too much of a surprise because internally the Sort method of both the Array and generic List<T> classes use the generic FunctorComparer<T> to wrap the delegate so that it can be used as an IComparer<T> object internally.  When the IComparer<T>.Compare method is invoked by .NET, it is actually the Comparison<T> delegate that is fired.  Pretty neat, uh?  The semantic of using this delegate (or the IComparer interface for that matter) is to define an alternative order for sorting elements within a collection.  Getting back to our toys collection, suppose we want to sort them by name (a string).  We could provide the following code to satisfy this requirement:

List<Toy> toys = Repository<Toy>.FetchAll();  // Again it doesn't matter how we get our toys

// using a lambda expression to define our sorting algorithm
toys.Sort((x, y) =>
           {
               if (x == y) return 0;

               if (x == null) return -1;

               if (y == null) return 1;

               return x.Name.CompareTo(y.Name);

           }
        );

This solution is great if you only have one sorting strategy and you foresee that it will not change in the future.  But there’s a better way to use this delegate.  In fact, the power of the Comparison<T> delegate is that…it’s a delegate!  This means that we can do some crazy and complex sorting if we must by combining various strategies!  What if we want to sort our toys first by name, then by price and also by a different criteria?  Using a lambda expression is asking way too much trouble.  Let’s see how we can take advantage of the Comparison<T> delegate in this case.  Let us now sort our toys by name, then by price.

private static void Main(string[] args)
{
    List<Toy> toys = Repository<Toy>.FetchAll();  // Again it doesn't matter how we get our toys

    // Instantiate our Comparison<T> delegate in a way that we want to sort our toys by name (first order), then by price (second order)
    Comparison<Toy> comparison = CompareToysByName;
    comparison += CompareToysByPrice;

    toys.Sort(comparison);
}

// Compare two toys by name
private static int CompareToysByName( Toy x, Toy y )
{
    if (x == y) return 0;

    if (x == null) return -1;

    if (y == null) return 1;

    return x.Name.CompareTo(y.Name);
}

// Compares two toys by price
private static int CompareToysByPrice( Toy x, Toy y )
{
    if (x == y) return 0;

    if (x == null) return -1;

    if (y == null) return 1;

    return x.Price.CompareTo(y.Price);
}

This is awesome because we can simply mix our sorting strategies through a simple delegate which will be used as a parameter to the Sort method of both an Array and generic List<T> classes.  Once the Sort method has finished its job, your collection will be sorted by the criteria you have specified. 

The Converter<TInput, TOutput> delegate

The next delegate that I would like to be familiar with is the generic Converter<TInput, TOutput> delegate which was introduced in .NET 2.0.  Just like its other counterparts, this delegate is being used by both the Array and generic List<T> classes, more specifically in their ConvertAll<TOutput> methods.  The signature of the Converter<TInput, TOutput> delegate is as follows:

public delegate TOutput Converter<TInput, TOutput>(TInput input)

This delegate is useful whenever you have to define a strategy to convert an object from one type to another type.  For example, you might want to convert an object of type System.Int32 to a type System.String.  Continuing with our toys example, let us consider the following simple requirement: we want to create a list containing only the names of every toy from our toys collection. 

List<Toy> toys = Repository<Toy>.FetchAll(); // Not really important how we get all our toys.

List<string> toysNames = toys.ConvertAll(toy => toy.Name);

It’s that easy!  Our strategy is basically that given a Toy (this is our closed type for TInput), we’ll return a String (this is our closed type for TOutput).  Just like we have done with the Comparison<T> delegate example, you can also mix in some conversion strategies.  Just remember that variance on delegates isn’t supported in C# 3.0.  For more information on this topic, I strongly suggest you to read Eric Lippert’s eleven-part posts on covariance and contravariance.

The Predicate<T> delegate

Though being used once again by the Array and generic List<T> classes, the generic Predicate<T> delegate is more used by the framework than the three other ones.  This delegate represents a method that defines a set of criteria and determines whether the specified object meets those criteria.  You can also see this delegate acting like a filter on a collection. The signature of the Predicate<T> delegate is as follows:

public delegate bool Predicate<T>(T obj)

Like I said, the .NET framework uses this delegate in both the Array and generic List<T> classes in many of their methods (Exists, Find, FindAll, FindIndex, etc.).  In short, you provide an evaluation context for a parameter where you either return true if the condition for that parameter is met, false otherwise.  Continuing with our toys example, suppose that we want to 1) find out whether we have a toy with a specific name and year, and 2) find all the toys that were made in Canada.  We could simply use the provided methods (Exists and FindAll) and passing them a Predicate<T> delegate that will contain our logic for evaluating whether or not the condition is satisfied.

List<Toy> toys = Repository<Toy>.FetchAll(); // We're not particularly interested in knowing how we got our toys.

// 1. We're interested in knowing whether we have my favorite Transformer of all: Megatron!  
// I have a couple of them, but I'm specifically interested in the one my parents bought me in 1985.
bool containsMy1985Megatron = toys.Exists( toy => toy.Name == "Megatron" && toy.Year = 1985 );

// 2. We're now interested in retrieving all our toys made in Canada.
List<Toy> myDecepticons = toys.FindAll( toy => toy.Country == "Canada" );

By simply invoking those methods and passing them a Predicate<T> delegate, I can concentrate on what I want in a more declarative way because I don’t have to explicitly iterate/loop over the collection with either a foreach statement, a for loop, a while loop, etc.  I just want to iterate over my toys, and either find out if a match was found or retrieve all my toys that satisfy some condition.  This last statement is also true for any of the other delegates that I presented here.

Conclusion

In this post, I wanted to familiarize you with some of the basic delegates that are offered by the .NET framework BCL (outside of ASP.NET, ADO.NET, etc.) that allow you more flexibility in specifying different strategies for various contexts (such as in finding, retrieving, converting or performing an action to an element of a collection).  In other words, these delegates allow me to concentrate more on the business logic rather than, for example, writing the plumbing necessary to iterate over a collection, because they are commonly used as a parameter to a method which already implements the plumbing on my behalf.

Whether I’m consulting with companies or training developers, more often than not I see these kind of delegates redefined in code because the developers were completely ignorant of the existence of these delegates!  That’s too bad, because violating the DRY principle forces you to document, test and maintain more code than you would actually need in your codebase.  Remember that the .NET framework isn’t solely C#.  The .NET framework is a huge toolbox that provides you with many tools (interfaces, classes, events, delegates, etc.) to build various applications.  The more you know about those tools and how to use them properly, the better your code will be and the more valuable you will become to your organization and team.

For more information on delegates, I highly recommend you the following links: