65.9K
CodeProject is changing. Read more.
Home

Chain some <T>hings

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.78/5 (5 votes)

Oct 9, 2015

CPOL
viewsIcon

5430

A small class to simplify creating an array with the help of a fluent interface... sort of.

Introduction

I was slightly tired of doing things that way

new T[]
{
      Foo
    , Bar
}

especially when I am forgetting the brackets (which happens way to often :doh:) and T is is similar to IStillCouldUseSomeMoreLettersAndAddSomeNumbersToo

Using the code

By using a different approach

class Chain<T> {

    private Chain() { }

    private readonly List<T> _Chain = new List<T>();

    public static Chain<T> Start => new Chain<T>();

    public Chain<T> this[T This_] {
        get { this._Chain.Add(This_); return this; }
    }

    public T[] End => this._Chain.ToArray();
}

it could be used like this

Chain<String>.Start
    ["Hello"]
    ["World"]
.End;

In short, it is nothing fancy, but for me it is quite usefull.