visual studio.net 2008 extension methods

January 8, 2008

Now that visual studio.net 2008 has been released developers have a much improved development environment and framework to produce high quality code with.  Extension methods are one of the new framework and IDE features that provides a powerful and clever method of extending objects that you do not have source code for or otherwise can’t directly extend.

Simply put, extension methods allow you to add new methods to the public contract of an existing type without sub-classing, decorating or recompiling the original type.  Prior to this release there were a few options available to solve this problem.

Read the rest of this entry »


nullable types and ado.net parameters

January 5, 2008

As most people are aware the .NET 2.0 framework supports nullable value types.  There are many articles on this topic and a few that address the issues of using nullable types in combination with your ado.net code.  However, most of these discuss the issue of using nullable types in combination with the DbDataReader objects, though few address the conflicts that arise when using a nullable type to set or get an ado.net parameter value.

Prior to .net 2.0 you’d run into this issue when attempting to pass a null string to the value of an input parameter.  In this case most of us would have written conditional code that looked something like this:


string firstName = null;
if(firstName == null) {
    Command.Parameters["FirstName"].Value = DBNull.Value;
} else {
    Command.Parameters["FirstName"].Value = firstName;
} 

Or you could have used a ternary operation: 


string firstName = null;
Command.Parameters["FirstName"].Value = firstName == null ? (object)DBNull.Value : firstName;

Read the rest of this entry »


system.nullable vs. tryparse

January 3, 2008

I’ve been working on some code tonight and needed to use the trusty struct.TryParse methods available in the core framework.  Unfortunately, the built in TryParse methods choke on nullable types.  After a frightfully short google search I ran across a blog entry from Steve Michelotti describing his approach to writing his own TryParse object for nullable types.  Its pretty sweet though it didn’t meet a specific need that I had, specifically the ability to have the result parameter have its value set to null in cases where the string passed in is in fact null (or empty).

I’ve modified his basic concept with an overloaded method that allows you to specify how the result parameter value will be set.  Passing true to the alwaysNull parameter will always set your value to null if the string sent to the function is null or empty (which is what I’m using for my code problem).  Conversely, passing false will result in the default behavior expected from the TryParse methods.


public static class NullableParser {
    private delegate bool TryParseDelegate(string s, out T result) where T : struct;
    private static bool TryParseNullable(string value, out Nullable result, TryParseDelegate tryParse, bool alwaysNull) where T : struct {
        if(string.IsNullOrEmpty(value)) {
            if(alwaysNull) {
                result = null;
                return false;
            } else {
                result = default(T);
                return false;
            }
        }
        T tempResult;
        bool success = tryParse(value, out tempResult);
        result = tempResult;
        return success;
    }

    public static bool TryParse(string value, out DateTime? result, bool alwaysNull) {
        return TryParseNullable(value, out result, DateTime.TryParse, alwaysNull);
    }
    public static bool TryParse(string value, out DateTime? result) {
        return NullableParser.TryParse(value, out result, false);
    }
} 

Clearly this needs to have the rest of the native value type methods completed, i.e. TryParseInt, TryParseDouble, TryParseBoolean, etc. though it illustrates the basic concept well.

Enjoy!


formatting source code on wordpress.com

January 1, 2008

I’ve been playing around with the word press features and wanted to post some source code.  For whatever reason it didnt want to format things the way that I wanted and after an hour or so of googling, I found that they’ve implemented a pretty sweet code formatting feature.  To give this a whirl take a look at the code below:


using System;

namespace MagicWebsiteAPI {
    /// <summary>
    /// Provides an interface that specifies a primary key or unique identifier for an object when stored in a storage medium such as a database or file.
    /// </summary>
    /// <typeparam name="TKey">The generic type that represents the type of data that the key is.</typeparam>
    public interface IKeyed<TKey> where TKey : struct {
        /// <summary>
        /// Gets a value that uniquely identifies an instance of the object in a storage medium.
        /// </summary>
        TKey? PrimaryKey { get; }
    }
}

What you’re seeing is an interface that I’ll commonly use in applications that I design.  The interface defines a nullable generic property named PrimaryKey that is typically used to track an objects primary key value in a database.  Its designed as nullable to support new objects that most likely do not have a primary key value assigned to them until after they are persisted to a database.

Additionally, the property is marked with only a get accessor.  Typically I design my objects with static factory methods for object creation (ie, retrieving from the database) which allows me to set the underlying field value without exposing a public set accessor of the property.  I’ll write more about this design pattern in another blog on another day.

Anyway, take a look at the original post that lead me to my first blog entry.