C# Yield Return in IEnumerable

Stop worrying about all the extra collections and sub-collections you have to create when you search a collection for those objects fitting certain criteria. We all do it on a daily basis, we create methods to search collections for all objects which fit certain criteria and we copy the located objects to a new temporary holder collection. Once the method has finished searching the entire source collection it then returns the temporary holder collection as its result.

Example Code:
private List GetPeopleWithSameName(string name, List srcPeople)
{
    List tempList = new List();
    foreach(Person p in srcPeople)
    {
        if(p.FirstName.Equals(name))
            tempList.Add(p);
    }
    return tempList;
}

What if we didn’t have to worry about creating and maintaining those temporary holder collections in our methods? What if we could get one of those located object at a time, at the very time it is found and pass it off for processing without waiting for the entire collection to be searched? Thanks to the new Yield Return construct we can.

How it works: When the .Net compiler sees the Yield Return construct it creates a nested private class which implements the IEnumerable, IEnumerator and IDisposable interfaces. This dynamically created class is pretty much a utility that maintains the state of your enumeration through the collection you are searching. Because this class tracks the state of the enumeration the method you created can return each object it finds which matches the criteria you set, and it returns it at the moment it finds it. Now we can compress our method as shown below.

Example Code:
private List GetPeopleWithSameName(string name, List srcPeople)
{
    foreach(Person p in srcPeople)
        if(p.FirstName.Equals(name))
            yield return p;
}

C# Custom Sorting using Anonymous Methods and the Comparer Generic

Quick and Concise sorting without all the extra code or bother of implementing custom sorting through interfaces, sound impossible? Here we will use a generic list full of a custom object type of our defining and we will sort it using Anonymous Methods and the generic Comparer class provided for us by the .Net framework.

Custom Class:

public class Book

{

public string ISBN { get; set; }

public string Title { get; set; }

public int Volume { get; set; }

}

On the Fly Sorting:

{

List library = new List();

//Add a bunch of books to the library collection here

//Sort the library alphabetically by Title

library.Sort( delegate (Book bookOne, Book bookTwo)

{

return Comparer.Default.Compare(bookOne.Title, bookTwo.Title);

});

//Sort the library by Volume number

library.Sort( delegate (Book bookOne, Book bookTwo)

{

return Comparer.Default.Compare(bookOne.Volume, bookTwo.Volume);

});

}

C# Anonymous Methods as Event Handler

As standard practice in .Net you create separate Event Handlers to handle the events of all controls on a form. In my personal code I always attempt to keep action code out of the event handlers and isolate it in its own method, this helps to keep things clean and easily altered if events change (see example below).

Example Code
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += Button1_Click;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            LoadSomeData();
        }

        private void LoadSomeData()
        {
            //Do something here.
        }

Now in .Net 2.0 we are allowed to use what are called Anonymous Methods. Anonymous Methods are code blocks which can be passed as (delegate) parameters to methods accepting delegates. Anonymous Methods allow us to get ride of extra methods and the overhead they create and simply pass an Anonymous Method. Because of this new feature instead of creating a separate method as an event handler to handle the button’s click event we can simply pass the Anonymous Method as the parameter using the delegate key word. This removes that extra method and reduces our code (see example below).

Example Code:
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += delegate(object sender1, EventArgs e1)
                                 {
                                     LoadSomeData();
                                 };
        }

        private void LoadSomeData()
        {
            //Do something here.
        }

This is of course an extremely simplified use of Anonymous Methods meant to be just an example of how they work, although simple it is still a valid use and may or may not help you in your code. In future posts I will attempt to show the use of Anonymous Methods in more complex scenarios but for now at least we understand what they are and how they can be used.

C# Casting Objects to Types

In .Net C# there are 3 ways to cast an object to a specific type. Implicit, Explicit and As. So what is the difference and why do I need to know?

Implicit Casting: this is where the system takes care of the casting for you with no extra code on your part. Implicit Casting happens when one type such as an Int is cast to a Double. Because an Integer is a whole number (having no decimal place) and a Double is a floating point number (having a decimal place) the conversion of lets say the Integer 5 to a double of 5.0 no information about the original Integer is lost (5 == 5.0). Because there is no loss of data the .Net system has no issue with making the conversion without warning you.

Code Example:
{
    int i = 5;
    double d = i;
}

Explicit Casting: in this case there is the possibility data may be lost in the conversion from one type to another and the system therefore will not take care of the cast itself, it requires you to make sure you know what you are doing and specifically tell it you are fine if data is lost in the conversion. Taking our previous example and just switching it around a Double 5.25 cast to a Integer of 5 causes a loss of data and thus a loss in precision because of this .Net requires you to verify its OK to dump the .25 from the Double.

Code Example:
{
    double d = 5.25;
    int i = (int)d;
}

Both of the above Casting options will return an exception if the casting is not possible for any reason at all, thus casting needs to take place within a Try-Catch block in order to handle these situations. If you don’t want to handle exceptions thrown by these 2 Casting options there is one more that is rarely used by developers, the AS keyword.

AS: the as keyword in .Net allows you to specify an Explicit Cast needs to happen but instead of an Exception being thrown if the cast is not possible a null value is simply returned. Now you only need to check if the value is null before continuing on with your code, if it is you then have the option to do some more processing to get the value you need. This limits the overhead and code that is needed to handle casting exceptions. Now there is a limitation to the use of the as operator, unfortunately it only performs reference conversions or boxing conversions.  It cannot perform conversions like user-defined conversions for these you will need to use Explicit Casting.

Code Example:
{
    double d = 5.25;
    int i = d as int;
}

C# Extension Methods

Microsoft has added a wonderful new addition to the .Net framework, Extension Methods! Extension methods allow you to add custom methods to already existing types (class) without the need to derive a new type from them or modify them (some of which you can’t such as built in .Net System types i.e. String, Int, Double). How it all works is these newly defined methods attach themselves to the type which they are referncing and can be used as if they are one of the original methods created at its inception. I good example of the perfect implementation of Extension Methods is the new LINQ library which when referenced in your code adds tons of new, fancy methods to collection types which implement the IEnumerable interface (there may be more to it than I have written here, but I am trying to be brief).

In order to set up your own custom Extension Methods within your assembly you need to define a Static Class which will hold all of these methods. Depending on the number of these methods you have for each type you wish to extend you may want to have a seperate Static Class for each of those types containing only the methods for that type. Extension Methods are Static just as the class that holds them.

Here is an example using the default System.String type:

public static class CustomStringExtensions

{
    public static bool ContainsQuestion(this String str)
    {
        return str.Contains('?');
    }
}

Now as long as you reference the assembly which contains this class every String object you use will automatically have the ContainsQuestion method.

C# Doubles and Divide By Zero (0) Gives no Exception

In a recent project there were several methods which performed various mathematical  calculations. One such method took in Doubles as parameters and performed several divides. According to the manner in which the method was written a Divide by Zero exception was to be caught if one of the doubles passed in was Zero. Unfortunately, no such exception was ever caught and strange results were being returned by the method thus corrupting the results of all calculations which called that method.

After some research I found out why. In C# Doubles are a form of Floating Point number, this means that they are to be used for scientific calculations and have been designed to never throw an exception because Zero is not their limit. According to the .Net documentation Doubles have a range supporting values from negative 1.79769313486232e308 to positive 1.79769313486232e308., this gives each Double a precision of ~29 digits. Because of this as the number approaches 0 it reaches a level of precision which is considered by the .net compiler as infinity and the results returned are either ‘Positive Infinity’ or ‘Negative Infinity’. Because Doubles are meant for Floating Point precision in scientific calculations you may need to select a less precise variable type to perform your calculations.