Creating collection with no code (almost)

When doing testing, I tend to create an object mother for the items generated multiple times for specifications. Quite often these objects need to be a part of a collection. A neat way to do so is to leverage .NET params mechanism:

    public static IEnumerable<T> CreateCollection<T>(params T[] items)
    {
      return items;
    }

And usage is the following:

private static IEnumerable<IPAddress> addresses = CreateCollection(new IPAddress(123456789), new IPAddress(987654321));

4 Comments

  • why wouldn't you do:
    private static IEnumerable addresses = new IPAddress[]{ new IPAddress(""), new IPAddress("")};

  • This seems pointless...... can't you just use object initialization syntax?
    private static IEnumerable addresses = new IPAddress[] { new IPAddress(123456789), new IPAddress(123456789) };


    It makes maintenance a nightmare when you fill your code with unnecessary library methods. It also makes it very hard for a new programmer to come in and work on your code when you use non-standard conventions and library functions.

    Every c# programmer knows object initialization, and will instantly understand what your doing with it, conversely no-one understands the purpose of "CreateCollection" until they look at the source code.

  • I wonder why you don't use:

    private static IEnumerable addresses = new [] { new IPAddress.... };

  • Sean, I might reconsider the name since you aren't really returning a Collection.

    I'm also leaning toward the other guys comments.

    For your specific scenario another, perhaps not as elegant for the implementation of the helper method, but easier for the consumer...

    IPAddress_ObjectMother.CreateMany(2)

    static IEnumerable CreateMany( int count )
    {
    return Enumerable.Range(1,count).Select(i => IPAddress_Mother.CreateOne());
    }

    Regardless, what you have is quite slick.

Comments have been disabled for this content.