Category: Code Tips

Code Tips

Anonymous Types in C# 3.0

For a long time, the var keyword has been the domain of only wholly dynamically typed languages. In fact, some people from the strongly-typed camp have considered the use of var as “hacky”, even though C#-ians have been able to treat everything as an object all along. Granted, it is not exactly the same and there is the whole boxing and unboxing thing to deal with, but I wanted to include full disclosure.

Now however, dynamic languages are all the rage and people are finding good uses for a generic variable type. To harness that power, one of the things done in C# 3.0 was the creation of Anonymous Types. Examine the code below and its output.

var blogPost = new
{
    Name = "Anonymous Types in C# 3.0",
    Author = "Pete Shearer",
    Category = "Code Tips"
}; 

Console.WriteLine(blogPost.Name);
Console.WriteLine(blogPost.Author);
Console.WriteLine(blogPost.Category);

Anonymous Types Output

By declaring my variable blogPost with the var keyword, I have created a dynamic variable. Now, after the new keyword and inside the curly braces, I declare a few properties and set their values. Behind the scenes, the compiler has declared a new object, given it a temporary name, and set the values in “traditional” fashion. It is even smart enough that if I declared another var with that definition, it wouldn’t redefine the anonymous type.

Within the anonymous type, the object remains strongly typed. Consider the following alteration to the code:

var blogPost = new
{
    Name = "Anonymous Types in C# 3.0",
    Author = "Pete Shearer",
    Category = "Code Tips",
    Date = new DateTime(2008, 3, 27)
}; 

Console.WriteLine(blogPost.Date.GetType());

Anonymous Types Output 2

The compiler inferred the type from the object placed into it. I know that I said new DateTime there, but it would have worked for any type that I put into that property. This new feature certainly affords developers a new level of flexibility. Enjoy.

Code Tips

C# Extension Methods

One of my favorite features of C# 3.0 is the extension method. An extension method basically allows you to add a method to a class without altering the class itself. All you need to do is declare some static methods with a “this” keyword in the parameters. .Net will then add this method on to whatever class you indicate is a parameter of the method (immediately following the “this” keyword). Then, as long as you have included the namespace in your using declarations in the code file, you are all set. Some examples would probably help. Here are some sample declarations.

public static class MyExtensions
{
    /// <summary>
    /// Validates (poorly) if an email address is in
    /// the right format.
    /// </summary>
    /// <param name="address">The email address to validate</param>
    /// <returns></returns>
    public static bool IsEmailAddress(this string address)
    {
        // Note: A purposely short pattern.  Not suitable
        // for enterprise-level validation
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        return regex.IsMatch(address);
    } 

    /// <summary>
    /// Determines the future datetime, given the number
    /// of minutes to go forward.
    /// </summary>
    /// <param name="minutes">Number of Minutes to Add</param>
    /// <returns></returns>
    public static DateTime MinutesFromNow(this int minutes)
    {
        return System.DateTime.Now.AddMinutes(minutes);
    } 

    /// <summary>
    /// Reverses the characters in a string. 
    /// This method should have been included in the base library.
    /// </summary>
    /// <param name="input">The string to be reversed</param>
    /// <returns></returns>
    public static string Reverse(this string input)
    {
        char[] inputArray = input.ToCharArray();
        Array.Reverse(inputArray);
        return new string(inputArray);
    }
}

You can see that I’ve created three methods and added XML comments to them (so I get intellisense on those methods later). Looking at the Reverse method, I declare it just like a normal method, “public static string Reverse” but then in the arguments, I just add a “this” before I set the parameter. So, instead of just “string input”, I have “this string input”. This tells .Net to add this method as an extension on the string class.

You can see from this example that I see my Reverse method in a string’s intellisense as well as my comments for the method.
Example of the Reverse() extension method

My total code to use each of my extension methods listed above is as follows.

static void Main()
{
    Console.WriteLine("Reversed String: {0}", "PeteOnSoftwareRules!".Reverse());
    Console.WriteLine("Now: {0}", System.DateTime.Now);
    Console.WriteLine("In 20 Mins: {0}", 20.MinutesFromNow());
    Console.WriteLine("president@whitehouse.gov: {0}", "president@whitehouse.gov".IsEmailAddress());
    Console.WriteLine("NotAnEmailAddress: {0}", "NotAnEmailAddress".IsEmailAddress());
}

When I run the code, I get the following results.
Example of the extension methods' output.

Good so far, but for now it seems like I am just changing how you would write some validation methods. Instead of IsEmailAddress(“a@b.com”), I am suggesting you write “a@b.com”.IsEmailAddress(). That is true so far. You could also create your own type that inherits from string and add a method, but then everyone else would have to use your type instead of the built-in .Net type. That’s not good at all. Additionally, extension methods add value by solving another problem.

Sometimes, you have to work with a framework or some third party class that has been sealed. I have for you the following example. It isn’t super useful, but concise, and will show my point 😉

public sealed class CannotInheritAndExtend
{
    public string FirstName = string.Empty;
    public string LastName = string.Empty; 

    public void PrintFirstName()
    {
        Console.WriteLine("First Name: {0}", this.FirstName);
    }
}

I really need this class to write out the last name, also. With this example, it is impossible to say “public class WillInheritAndExtend : CannotInheritAndExtend” and then just add my own method. Go ahead and try. You will get a beautiful compiler error. What you can do, however, is the following:

public static void PrintLastName(this CannotInheritAndExtend input)
 {
    Console.WriteLine("Last Name: {0}", input.LastName);
 }

Now my method is included in intellisense for the original class.
Intellisense for the new method on the sealed class.

So, now I can have this code

CannotInheritAndExtend a = new CannotInheritAndExtend();
a.FirstName = "pete";
a.LastName = "shearer";
a.PrintFirstName();
a.PrintLastName();

that produces the desired output.
Results of new method on the sealed class.

As you can see, extension methods are really very helpful. They allow you to keep original types intact, but extend functionality onto them. I hope you find them as useful and cool as I do.

Code Tips

Code Tip: C# Coalesce

I have to admit something. I’m something of a Sql Coalesce() fan. I know that Sql Server has an IsNull() function, but there are two bad things about it. First, it is proprietary to Sql Server and I like to try to write my Sql as close to ANSI as I can so that I don’t build up too many bad habits that cause me to have problems when I have to work in other DB platforms. Secondly, IsNull() only takes one option (well, you could nest your IsNull() statements, but that is unwieldy). Coalesce() lets you give a list of items and just takes the first one of them to not be null. Apparently, IsNull() is also slower. All hail, Coalesce()!!!

Several months ago, I was doing some coding in C# and I was actually wishing that C# had a Coalesce function so that I could not have to do a bunch of manual null checking in my code. On a whim, I decided to Google C# Coalesce and see if someone had written one or if there was one hidden in the framework somewhere. To my surprise, I found that C# did have such an animal. Here is an example of its use.

// Checks the HTML Form for a value,
// if that wasn't submitted, use the value
// potentially set elsewhere in the code,
// if that is null, set the variable to
// a blank string.
string value = Request.Form["someField"] as string ?? someVariable ?? string.Empty;

I can’t tell you how much I love having this.