Click here to Skip to main content
15,880,608 members
Articles / Programming Languages / C#
Tip/Trick

Chain some <T>hings

Rate me:
Please Sign up or sign in to vote.
2.78/5 (5 votes)
8 Oct 2015CPOL 5.2K   4
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

C#
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

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

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Germany Germany
- Born at the dawn of the Video Game Consoles
- Hacked his way through a C64 by Assembler
- Survived the hard times with an Amiga
- Got hit by Delphi on PC in the mid-90s
- Sinned with VB6
- Redeemed by C++ and C#

Comments and Discussions

 
GeneralThis trick is hard to understand. I'd rather to add one by one. Pin
LoveJenny8-Oct-15 22:48
LoveJenny8-Oct-15 22:48 
This trick is hard to understand. I'd rather to add one by one.
GeneralRe: This trick is hard to understand. I'd rather to add one by one. Pin
StM0n9-Oct-15 0:03
StM0n9-Oct-15 0:03 
GeneralRe: This trick is hard to understand. I'd rather to add one by one. Pin
#realJSOP9-Oct-15 1:34
mve#realJSOP9-Oct-15 1:34 
GeneralRe: This trick is hard to understand. I'd rather to add one by one. Pin
StM0n9-Oct-15 2:15
StM0n9-Oct-15 2:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.