Sunday, March 15, 2009

.Net Reflection Part 2. Loading Assemblies at runtime.

In my first post about Reflection, I gave a basic demo of what can be done using reflection. How you can access metadata about a class such as properties etc. In this post, I'd like to dig a bit deeper into Reflection and show the true power of Reflection and what can be accomplished.

As you may or may not know, Visual Studio has many great addons that can be found across the web. Basically, Microsoft has an API that developers can code against, and then "plugin" their addons into Visual Studio. How is this accomplished? How does it know how to load the code I wrote into Visual Studio? The basic idea behind this is a simple Plugin System that can be accomplished using Reflection. I'll demonstrate the basic premise here to give you a simple understanding of how this all works. This post will be more of a tutorial kind of deal so follow along with me as I go through the steps and I explain them.

Before we do any code, let me explain the basic idea of what we'll do. We're going to create an Interface that we'll call IPluginInterface which will have one simple get property called "Name". All "plugins" will have to implement this interface. At runtime, we will then look in a specific folder for any dll files that have types that implement this interface. If it does, then we know it's a plugin, and we can load it up into our app. May not make sense now, but bear with me. It'll all make sense once we start coding.

OK, fire up Visual Studio and create a Console Application callaed "AssemblyLoadingDemo". Change the default namespace to: SetFocusDemo.Reflection.Demo. You should now see this:

    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5 
    6 namespace SetFocusDemo.Reflection.Demo
    7 {
    8     class Program
    9     {
   10         static void Main(string[] args)
   11         {
   12 
   13         }
   14     }
   15 }

OK, for now we won't do anything in this project. Now Click on File -> New -> Project and select "Class Library". Call it "PluginInterface". Get rid of the default Class1.cs, and add a class called "IPluginInterface.cs". Then, add this code to the interface:

namespace SetFocusDemo.Reflection.Contract
{
    /// 
    /// This interface will need to be implemented by any class that wants to be a plugin
    /// in our Demo Plugin project.
    /// 
    public interface IPluginInterface
    {
        string Name { get; }
    }
}

Simple interface, doesn't do much really except it has the Name getter like we talked about. In a real life scenario, you would probably have multiple interfaces with multiple methods and properties, but again this is just a demo, so one is enough. Also, please note that I put this in the "SetFocus.Reflection.Contract" namespace.

OK, now, let's actually create a few "Plugins". Basically they'll be classes that will implement this interface.First, let's create another Project. Click File -> New -> Project and create a Class Library called "Plugin Library". Then, right click on "References" and click "Add Reference". Select the Projects tab on top and click select the "Plugin Interface" assembly. Once that's done, remove the default "Class1.cs" and add a new class called "CustomPlugin1". Then, add this code:

namespace PluginLibrary
{
    using SetFocusDemo.Reflection.Contract;
public class CustomPlugin1 : IPluginInterface
    {
        public string Name
        {
            get { return "Custom Plugin 1"; }
        }
    }
}

Doesn't do all that much, but it implements the IPluginInterface and just returns it's name. Now, add another class to this project, and call it "AnotherPlugin". Then add this code:

namespace PluginLibrary
{
    using SetFocusDemo.Reflection.Contract;
public class AnotherPlugin : IPluginInterface
    {
        public string Name
        {
            get { return "Another Plugin"; }
        }
    }
}

Same thing as before really. Another class that implements the same interface. Now, click on the Build menu and click "Build PluginLibrary". Once that's done, right click on the "Plugin Library" project on the right side in solution explorer and click on "Open Folder in Windows Explorer". Then, go to the Bin -> Debug folder and copy the "PluginLibrary.dll" file. Then, open your MyDocuments folder and paste it in there.

OK, we finally have all the code set up to actually write our Plugin Loader. This is where the Reflection magic will happen. Go back to the first project that we called "AssemlyLoadingDemo". First, add a reference to the "Plugin Interface" project and add the using statement on top: "using SetFocusDemo.Reflection.Contract;" Add a new class and call it "PluginLoader.cs". This class will have one static method that will return an array of all the IPluginInterface objects it found and created. Here's the actual code of the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SetFocusDemo.Reflection.Contract;
using System.IO;
using System.Reflection;
 
namespace SetFocusDemo.Reflection.Loader
{
    public class PluginLoader
    {
        public static IPluginInterface[] GetPlugins(string directory)
        {
            if (String.IsNullOrEmpty(directory)) { return null; } //sanity check
 
            DirectoryInfo info = new DirectoryInfo(directory);
            if (!info.Exists) { return null; } //make sure directory exists
 
            List<IPluginInterface> plugins = new List<IPluginInterface>();
            foreach (FileInfo file in info.GetFiles("*.dll")) //loop through all dll files in directory
            {
                //using Reflection, load Assembly into memory from disk
                Assembly currentAssembly = Assembly.LoadFile(file.FullName); 
 
                //Type discovery to find the type we're looking for which is IPluginInterface
                foreach (Type type in currentAssembly.GetTypes())
                {
 
                    if(!type.ImplementsInterface(typeof(IPluginInterface)))
                    {
                        continue;
                    }
 
                    //Create instance of class that implements IPluginInterface and cast it to type
                    //IPluginInterface and add it to our list
                    IPluginInterface plugin = (IPluginInterface)Activator.CreateInstance(type);
                    plugins.Add(plugin);
                }
            }
 
            return plugins.ToArray();
        }
    }
}

There's alot of code here, I know and I'll do my best to explain. Before I do that though, two things to note. First, you'll see a using statment on top to System.Reflection. Secondly, you'll see this line of code: type.ImplementsInterface(typeof(IPluginInterface)) but that's an extension method I wrote. (For more on extension methods, see my blog post about them here.) Right click on the project and add a class called "TypeExtensions". Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SetFocusDemo.Reflection.Loader
{
    public static class TypeExtensions
    {
        public static bool ImplementsInterface(this Type type, Type interfaceType)
        {
            return type.GetInterfaces().Contains(interfaceType);
        }
    }
}

Simple method that checks to see if a given type implements a specific interface.

OK, now we can go back and explain what's going on here.

The GetPlugins method takes a directory name as it's parameter indicating where we want to check for plugins. First we just do some sanity checking to make sure we don't get any Null Reference Exceptions:

     if (String.IsNullOrEmpty(directory)) { return null; } //sanity check
     DirectoryInfo info = new DirectoryInfo(directory);
     if (!info.Exists) { return null; } //make sure directory exists

Now we know our "info" object points to the directory we want to look for Plugins.

List<IPluginInterface> plugins = new List<IPluginInterface>();

Here we just new up a List that will be used to add the plugins found and returned from the method.

foreach (FileInfo file in info.GetFiles("*.dll")) //loop through all dll files in directory
            {
Here we start enumerating all the files in the directory to find dll files. Note: in a real world app, this can be dangerous. You're loading dll's into your app without really knowing that they're safe. In a real world, you'd load them into a seperate app domain, but that's out of the scope of this post.

     //using Reflection, load Assembly into memory from disk
     Assembly currentAssembly = Assembly.LoadFile(file.FullName);

Here we actually load the Assembly from the DLL file found. The Assembly class had many great methods on it which allows you to do all kinds of stuff at runtime. In our case, we'll just be looking through the assembly to find a "Plugin":

 //Type discovery to find the type we're looking for which is IPluginInterface
                foreach (Type type in currentAssembly.GetTypes())
                {
Now, we loop through all the Types found in the Assembly. GetTypes() returns an Array of all the Types found in that assembly. That includes classes, interfaces etc.

      if(!type.ImplementsInterface(typeof(IPluginInterface)))
      {
         continue;
      }

Here we look at the type to see if it implements our interface. The idea here is, if a class wants to be a plugin to our App, it MUST implement our IPluginInterface. If it doesn't it can't be a plugin, in which case we just "continue" and go to the next type found in the Assembly.

            //Create instance of class that implements IPluginInterface and cast it to type
           //IPluginInterface and add it to our list
           IPluginInterface plugin = (IPluginInterface)Activator.CreateInstance(type);
           plugins.Add(plugin);

If we DID find a type that implements our interface, then we actually Create an Instance of that type using Activator.CreateInstance(type). We then cast it to the type of our interface, and add it to our list. Activator.CreateInstance is a really cool method that allows you to dynamically load up objects at runtime.

Finally we clost up and return the List as an array:

return plugins.ToArray();

Ok, we now have all the code to give this a wirl. Go back to your Program.cs and in the main method add this code:

static void Main(string[] args)
        {
            //load plugins from MyDocuments. This is just a demo, in a real scenario, you'd use some
            //specific custom folder
            IPluginInterface[] plugins = PluginLoader.GetPlugins(
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
 
            foreach (IPluginInterface plugin in plugins)
            {
                Console.WriteLine("Plugin: \"{0}\" was found and loaded.", plugin.Name);
            }
 
            Console.ReadLine();
        }

Basically, call our static method that loads up the plugins, loop through them and print out the name. Here's the output you should see:

Plugin: "Custom Plugin 1" was found and loaded.

Plugin: "Another Plugin" was found and loaded.

What happened here? Basically, we copied our "Plugins" to our MyDocuments folder. When our PluginLoader went to look for Assemblies, it looked in the MyDocuments folder, and found our PluginLibrary.dll. It then loaded up the assembly and looked through the Types found there. It found "CustomPlugin1" and "AnotherPlugin". Then, it actually created instances of each of those classes and cast them as IPluginInterface. This is key! At design time, we have NO idea what the type we'll be. Any developer coding against our IPluginInterface API can create their own class that implements IPluginInterface. We have no clue what his class will be. What we DO know is that it will be of type IPluginInterface. Therefore, when we create an instance of it using Activator.CreateInstance, and cast it to the only type we know of which is IPluginInterface. Then, we can call the methods on our interface which in our cast is the Property "Name".

This post turned out to be alot longer than I thought. There's alot happening here, so if you have any questions, seriosuly, email me at a.friedman07@gmail.com or post a comment here.

Friday, March 13, 2009

.Net Reflection, hey look I can see myself!

Towards the end of Week 1 in the Master's Program, we touched on Reflection and were shown how they can be used with attributes. Here's a quick review. Let's decorate our Person class we keep using with a Description attribute.

   63     [Description("This represents a Person's basic information.")]
   64     public class Person
   65     {
   66         public string FirstName { get; set; }
   67         public string LastName { get; set; }
   68         public int Age { get; set; }
   69     }

What we were taught that first week was how to get the information from an attribute at runtime. Here's a simple way of doing it. In fact, just to make it a little more interesting, let's actually make this an extension method on object, so that any time an object has a Description attribute, we could simple do this:

   57 string description = myObject.GetDescription();

Here's how we can do it:

   72     public static class ObjectExtensions
   73     {
   74         public static string GetDescription(this object o)
   75         {
   76             Type type = o.GetType();
   77             object[] attributes = type.GetCustomAttributes(typeof(DescriptionAttribute), false);
   78             if (attributes.Length == 0)
   79             {
   80                 return String.Empty; //no Description attribute found
   81             }
   82 
   83             DescriptionAttribute description = (DescriptionAttribute)attributes[0];
   84             return description.Description;
   85         }
   86     }

The Type class is what really gets us started. Every object in the .NET Framework has a method called GetType() which returns a Type object. You can also get the type by using the typeof keyword to get you a speficic type. IE: If you want the "Type" of our Person object, you would do:

   58 Type personType = typeof(Person);

So if you have an object, you can call GetType() however if you don't actually have an object, but you need to get information about a sepcific Type (class), you use the typeof keyword. So in our example, we first get the Type from the object passed in, and then we use the methods on the Type class to retrieve the attributes. This is the tip of the iceberg for Reflection. Reflection is unique in the sense that you're actually examining the type of a specific class at runtime. Generally when dealing with an object, you get the values of a specific object, such as the Person's Name, or a Car's Color etc.. Reflection on the other hand tells us about the class (type) itself.

Getting attributes is just the beginning. You can do alot of really cool things with Reflection, and I'll try to demonstrate a few of them.

Using Reflection, you can get all the members of a class. You can get the Properties, Members, Methods etc. If you remember, during the first project at SetFocus, we had a requirement like this:

Provide a named enumerator called PropertyAndValuesCollection that allows for easy enumeration over a set of string values that provide information about the current Supplier object. The string values returned by the enumerator should take the user over all of the property values of the current Supplier object in the output format of: PropertyName: PropertyValue.
We had to have a method that returned all the Properties and their values of a Supplier object. So, not knowing much about reflection, most of us did something like this:

  182         public  System.Collections.IEnumerable PropertyAndValuesCollection()
  183         {
  184             yield return "ID: " + ID;
  185             yield return "CompanyName: " + CompanyName;
  186             yield return "ContactName: " + ContactName;
  187             yield return "ContactTitle: " + ContactTitle;
  188             yield return "Address: " + Address;
  189             yield return "City: " + City;
  190             yield return "Region: " + Region;
  191             yield return "PostalCode: " + PostalCode;
  192             yield return "Country: " + Country;
  193             yield return "Phone: " + Phone;
  194             yield return "Fax: " + Fax;
  195             yield return "HomePage: " + HomePage;
  196             yield return "Type: " + Type.ToString();
  197         }

This worked, and the TestHarness considered this to be OK. However, hardcoding anything sucks! What if you add/remove properties of this supplier class, now you have to remember to go change this method. Wouldn't it be better if we can just examine the class at runtime and return all the properties? Well, here's how you can do it using Reflection:
  183  public IEnumerable PropertyAndValuesCollection()
  184         {
  185             Type type = this.GetType();
  186             PropertyInfo[] infos = type.GetProperties();
  187             for (int i = 0; i<infos.Length;i++)
  188             {
  189                 yield return String.Format("{0}: {1}", infos[i].Name,
infos[i].GetValue(this, null));
  190             }
  191         }

I tested this with the TestHarness and it does in fact pass. What's happening here is very simple. First we get the Type of this class (Supplier). We could also have done Type type = typeof(Supplier). Same thing, doesn't matter. Then, we call the GetProperties method on the type object that returns an array of PropertyInfo objects. The PropertyInfo class has a property on it called Name which is just that, the name of the actual property. Then, this is where reflection really shines, it has a method called GetValue. This method enables us to actually get the value of an object at runtime!

Here's another demonstration of when this can be useful. Say you want to add a ToXml() method to your class that writes out all the values of your class to an XML string. (Yes, I know there are already classes in the .NET Framework that do this, but even wonder how they do it? :) ) Here's a simple code sample. We'll add this to our Person class:

   72 [Description("This represents a Person's basic information.")]
   73     public class Person
   74     {
   75         public string FirstName { get; set; }
   76         public string LastName { get; set; }
   77         public int Age { get; set; }
   78 
   79         public string ToXml()
   80         {
   81             Type type = this.GetType();
   82             StringBuilder builder = new StringBuilder();
   83             StringWriter stringWriter = new StringWriter(builder);
   84             XmlTextWriter writer = new XmlTextWriter(stringWriter);
   85             writer.WriteStartDocument();
   86             writer.WriteStartElement(type.Name);
   87             foreach (var prop in type.GetProperties())
   88             {
   89                 writer.WriteAttributeString(prop.Name,
prop.GetValue(this, null).ToString());
   90             }
   91             writer.WriteEndElement();
   92             return builder.ToString();
   93         }
   94     }

Now let's say we have a Person object like this:

   25             Person p = new Person
   26             {
   27                 FirstName = "Alex",
   28                 LastName = "Friedman",
   29                 Age = 27
   30             };

Now, let's call our ToXML method:

   32 string xml = p.ToXml();

This would be the result:

   37 <?xml version="1.0" encoding="utf-16"?><Person FirstName="Alex" LastName="Friedman" Age="27" />


Not very pretty, but you get the point!

In future posts, I'll dig deeper into Reflection and show some even more crazy stuff you can do like loading Assemblies at runtime and invoking methods on them.

Monday, March 2, 2009

New Features in C# 3.0 / .NET 3.5 Part 2

This is part 2 of the New features found in C# 3.0 / .NET 3.5. The first post can be found here.

The next thing I'd like to cover is something called "Lambda Expressions". This is a bit more of a complicated one, so I'd like to first start by giving a background on Predicates and Anonymous Functions.

Let's start out again with our Person class from the previous post:

   54         public class Person
   55         {
   56             public string FirstName { get; set; }
   57             public string LastName { get; set; }
   58             public int Age { get; set; }
   59         }

Now let's load up a List with a few Person objects.

   27             List<Person> people = new List<Person>
   28             {                
   29                     new Person { FirstName = "Alex",
   30                     LastName = "Friedman", Age = 27 },
   31                     new Person { FirstName = "Jack",
   32                     LastName = "Bauer", Age = 45 },
   33                     new Person { FirstName = "Cloe",
   34                     LastName = "O'Brien", Age = 35 }
   35             };

The List class in .NET has a FindAll method which takes a Predicate and returns a List. Let me explain:

   19 public delegate bool Predicate<T>(T obj)

That's the signature for the Predicate delegate. Basically, it takes as a parameter an object of type T and returns a bool. So here's a simple use of the find all method using a Predicate. Let's assume we want to find all the people in our List that are older than 30. Here's how we'd use the FindAll method to accomplish this.

First, let's write a method that takes a Person object, and returns a true/false if the person is older/younger than 30:

   47         private bool IsOlderThan30(Person p)
   48         {
   49             return p.Age >= 30;
   50         }

Nothing fancy, simple method. Now, let's create a Predicate that will reference this method:

   56 Predicate<Person> olderThan30 = new Predicate<Person>(IsOlderThan30);


So now, at this point, our olderThan30 Predicate "points" to our IsOlderThan30 method. Now, we can call the FindAll method on our List:

   68 List<Person> result = people.FindAll(olderThan30);


This will return a List of two Person objects. One for "Jack Bauer" who we listed as 45, and one for "Cloe" who is 35. I think it's helpful at this point to understand how this works. Let's take a look at Reflector (if you don't have Reflector, get it now! That thing is awesome. You can grab it here.) to see what the FindAll method looks like under the covers:

   54         public List FindAll<T>(Predicate<T> match)
   55         {
   56             if (match == null)
   57             {
   58                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
   59             }
   60             List<T> list = new List<T>();
   61             for (int i = 0; i < this._size; i++)
   62             {
   63                 if (match(this._items[i]))
   64                 {
   65                     list.Add(this._items[i]);
   66                 }
   67             }
   68             return list;
   69         }

Basically, it loops through all the items in the collection, and passes each one of them to the method that we passed in as a Predicate. Confused yet? We passed in a Predicate which pointed to a method that took a Person object and returned a bool. The FindAll method, takes each of our Person objects, passes it to our IsOlderThan30 method (that we referenced through our Predicate) and grabs the result. If it returns true, it adds it to a list and then returns that List. A bit confusing, but it's kinda cool actually.

This is all straightforward delegate stuff. Now, here's what .NET 2.0 brough to the table; something called "Anonymous Methods". The idea is simple: We will never use the IsOlderThan30 method ourselves, so why bother writing out a whole method. Anonymous Methods allow us to create the entire method right there when passing it into the FindAll method. Let me demonstrate:

   70             List<Person> result = people.FindAll(delegate(Person p)
   71             {
   72                 return p.Age >= 30;
   73             });

And that's all. We can now eliminate our IsOlderThan30 altogether, and do it all inline. The compiler turns that into an actual method behind the scenes, and then when FindAll is called, it calls that method for each object in this list.

Now, in .NET 3.5 there's something called "Lambda Expressions". Basically, Lambdas are Anonymous Functions, but with an even more tidy syntax. Here's the FindAll method using Lambdas:

   70             List<Person> result = people.FindAll(p => p.Age > 30);


The "=>" is the lambda operator. The "p" is the parameter that will be passed to our anonymous function. It's a bit confusing at first, but it's basically an anonymous function where the compiler can infer the type. Since the FindAll method requires a Predicate where T is a Person object, the compiler can figure out that the "p" being passed to the Lambda is of type Person.

I think another example would help. Say we have a Windows Form with a button on it. On button_click we want to show a MessageBox with today's Date. Here's how we'd normally do it:

   16         public Form1()
   17         {
   18             InitializeComponent();
   19             this.button1.Click += new System.EventHandler(this.button1_Click);
   20         }
   21 
   22         private void button1_Click(object sender, EventArgs e)
   23         {
   24             MessageBox.Show(DateTime.Now.ToShortDateString());
   25         }

It's useful again to go back to the basics and understand what's happening here. The Click Property of the Button class is an event which is basically a delegate. We then assign it a new delegate of type EventHandler that's pointing to a function called "button1_Click". When the event is "raised" (when the delegate is called) it calls our function. Here's how we can rewrite this using Lambda Expressions:

   20             this.button1.Click += (o,e) =>
   21             {
   22                 MessageBox.Show(DateTime.Now.ToShortDateString());
   23             };

The thing to note about the syntax is this. If there are no parameters being passed, you do this:

   20 () => //empty parentheses


If there's only one parameter, then parentheses are optional. If there are two or more parameters, then parentheses are required.

To summarize, it's crucial to have a good understanding of delegates and anonymous methods before messing with Lambda Expressions. However, they're used all over LINQ (which I hope to cover in future posts) so I suggest you mess around with these to get a good understanding of them.

New Features in C# 3.0 / .NET 3.5 Part 1

In the first few blog posts, I’d like to start out by covering the new features introduced along with C# 3.0 and .NET 3.5. Some of these things are specific to the language itself, and can technically run against older versions of the Framework, while others are new things that are part of the actual .NET Framework 3.5. I’ll point out which ones which as I go.



Note: In order to take advantage of these features, Visual Studio 2008 is required. If you don’t already have a copy of VS2008, you can download the free express version here.

The first thing I’d like to talk about is a simple yet great feature called "Automatic Properties." The basic idea is as follows: Typically, when you want to have a public property on a class, you would have a private variable at the class level, and then have a get/set property for that variable:

   12         private string firstName;
   13 
   14         public string FirstName
   15         {
   16             get { return this.firstName; }
   17             set { this.firstName = value; }
   18         }

Nothing we haven’t done many many times. However, now, you can eliminate the private variable altogether, and just do this:

   12 public string LastName { get; set; }


Yup, that’s it! The interesting thing here is that it’s really just compiler trickery. Behind the scenes, the compiler does create a backing field for you, and a full blown Property. Let’s look at the IL generated by the compiler for both of those properties:


As you can see, the compiler generated a private string for me, and called it k_BackingField. Very cool. Trust me, once you start using these, you’ll never look back!

There is one thing to point out though; when using Automatic Properties, your get and set methods can have no logic whatsoever. If you want to do any validation in your getter or for example raise an event in your setter, you’ll need to do it the regular way and create your own backing variable.


Next up, is “Object Initializers.” Let’s create a simple class, we’ll call it Person. We’ll have three (Automatic) Properties. FirstName, LastName, and Age:

   34         public class Person
   35         {
   36             public string FirstName { get; set; }
   37             public string LastName { get; set; }
   38             public int Age { get; set; }
   39         }


Take note that this class has no constructor. Therefore, if I’d want to instantiate a Person object and set all it’s values, I’d have to do something like this:


   27          Person alex = new Person();
   28          alex.FirstName = "Alex";
   29          alex.LastName = "Friedman";
   30          alex.Age = 27;


Again, nothing fancy that you haven’t done before. However, say if we have an object that we need to set many properties on, this can get ugly quickly. Well, here’s the cool new way of doing it:

   27             Person alex = new Person
   28             {
   29                 FirstName="Alex",
   30                 LastName="Friedman",
   31                 Age=27
   32             };


You can set all properties this way, or only a select few that you want. Either way, it just saves you from having to type object. over and over again.

Intellisense makes it even easier for you. As soon as you open that first curly brace you get a list of all the available Properties you can set:


Taking these Object Initializers one step further, there’s also a new feature called “Collection Initializers.” Say you wanted to have a List with 3 Person objects. Here’s how you would normally do it:

   27             List<Person> people = new List<Person>();
   28             people.Add(new Person
   29             {
   30                 FirstName = "Alex",
   31                 LastName = "Friedman",
   32                 Age = 27
   33             });
   34             people.Add(new Person
   35             {
   36                 FirstName = "Jack",
   37                 LastName = "Bauer",
   38                 Age = 45
   39             });
   40             people.Add(new Person
   41             {
   42                 FirstName = "Cloe",
   43                 LastName = "O'Brien",
   44                 Age = 35
   45             });
   46             //Yes, before anyone asks, I'm a big fan of 24 :)



Now, you can do all that in one line when instantiating the collection:

   27             List<Person> people = new List<Person>
   28             {                
   29                     new Person { FirstName = "Alex",
   30                     LastName = "Friedman", Age = 27 },
   31                     new Person { FirstName = "Jack",
   32                     LastName = "Bauer", Age = 45 },
   33                     new Person { FirstName = "Cloe",
   34                     LastName = "O'Brien", Age = 35 }
   35             };


The last topic I’d like to cover in this post (which is probably also one of my personal favorites) is something called “Extension Methods.” In short, extension methods allow you to add functionality to existing classes. The best way to demonstrate, is by example. Very often, it’s useful to be able to check a string if it’s all numeric. (For validation, or whatever, doesn’t really matter). Extension methods now allow you to “add” these methods on to the string class as if it were part of the string class. Here’s how it’s done:

   48         public static class StringExtensions
   49         {
   50             public static bool IsNumeric(this string s)
   51             {
   52                 foreach (char c in s)
   53                 {
   54                     if (!char.IsDigit(c))
   55                     {
   56                         return false;
   57                     }
   58                 }
   59                 return true;
   60             }
   61         }


Simple method, just loop through the characters of the string, and if it’s not a digit return false, otherwise return true. (It doesn’t take into account $ signs and comas, but doesn’t really matter for this example). I’d like you to notice the syntax. When declaring an extension method, you use the “this” keyword in the method signature. Also, of note, extension methods MUST be declared in a static class, and MUST be static methods. Now here’s the cool part. Here’s how you’d use this method:

98 string number = "12345";

99 bool result = number.IsNumeric();


As you can see, it looks as if IsNumeric is actually part of the string class! This feature is extremely popular, and will be real important when I get to covering LINQ. There are many libraries out there that have tons of extension methods. Some are great, some are excessive in my opinion, but the point is all the same. Extension methods are awesome!

The thing to note about extension methods is that it's really just compiler trickery. The compiler basically takes the method call to the extension methods and turns it into something like this:

   37       string number = "12345";
   38       bool result = StringExtensions.IsNumeric(number);

I'll let you decide which way looks cooler and cleaner :)

One more thing about Extension Methods; here’s what it looks like in VS’s Intellisense:

That little blue arrow pointing down next to IsNumeric shows that this is an extension method.

Well, that’s it for the first post. I’ll cover more new topics in my next few posts.