Thursday, October 27, 2005

Singletons and Dynamic Loading Assemblies

Again in the pits of the coding jungle I discovered that we were breaking the Singleton design pattern. Basically what we had were public default constructors. This of course would allow anyone or any dynamic assembly loader to create a new instance of what should be a unique object!

To solve this I decided to augment our dynamic loading class to look for an attribute: [SingletonAttribute] or [Singleton]. If it finds this, then it will look for [SingletonInstance] that should be on a public static getter.

Old code:

public class NotQuiteSingleton

{

    private static NotQuiteSingleton _instance = new NotQuiteSingleton();

 

    public static NotQuiteSingleton Instance

    {

        get

        {

            return _instance;

        }

    }

 

    /// REALLY BAD!

    public NotQuiteSingleton()

    {

    }

}



New code:

[Singleton]

public class AuthenticSingleton

{

    private static AuthenticSingleton _instance = new AuthenticSingleton();

 

    [SingletonInstance]

    public static AuthenticSingleton Instance

    {

        get

        {

            return _instance;

        }

    }

 

    // Ahhhh... much better...

    private AuthenticSingleton()

    {

    }

}



Enjoy,

John

Wednesday, October 26, 2005

In my stumbling through code I often come across code that looks like:

string bar = "this is some&string&to be split";
char[] foo = new char[1];
foo[1] = '&';
string[] splitString = bar.Split(foo);

Digging into the documentation on string.Split() you find that there are two versions:

public string[] Split(char[], int);

and
public string[] Split(params char[]);
The second is of interest to us because of the 'params' keyword. Those of you familiar with the Console.WriteLine() call (or printf() from the old C days) will recognize that 'params' allows us to supply a parameter list of unknown size and pass it into a function. In this case, the Split() call can be made with a single '&' parameter instead of making it into an array. So we get the following:

string bar = "this is some&string&to be split";
string[] splitString = bar.Split('&');

Also note that if we needed to add another character to split on, say a space, we would write the split like this:

string[] splitString = bar.Split('&', ' ');

Simple, elegant and more in touch with your C# self :)