maxp
maxp

Reputation: 25141

Shortest inline collection initializer? C#

What is the neatest / shortest way I can write an inline collection initializer?

I dont care about reference names, indexes are fine, and the item only needs to be used in the scope of the method.

I think an anonymous type collection would be messier because I would have to keep writing the key name every time.

I've currently got

var foo = new Tuple<int, string, bool>[] 
{ 
   new Tuple<int, string, bool>(1, "x", true), 
   new Tuple<int, string, bool>(2, "y", false) 
};

Im hoping c# 4.0 will have something ive missed.

Upvotes: 15

Views: 3941

Answers (3)

tzot
tzot

Reputation: 95931

You can also add a

using MyTuple= System.Tuple<int, string, bool>;

at the end of your using declarations and then use MyTuple instead of the longer version.

Upvotes: 0

Random Dev
Random Dev

Reputation: 52280

a bit less space in there if you use Tuple.Create(1,"x",true) instead of the new thing - and you can strip the new Tuple<tint, string, bool> stuff before the array too:

var foo = new [] { Tuple.Create(1, "x", true), Tuple.Create(2, "y", false) };

or take this one:

Func<int, string, bool, Tuple<int, string, bool>> T = (i, s, b) => Tuple.Create(i,s,b);
var foo = new [] { T(1, "x", true), T(2, "y", false) };

or even

Func<int, string, Tuple<int, string, bool>> T = (i, s) => Tuple.Create(i,s,true);
Func<int, string, Tuple<int, string, bool>> F = (i, s) => Tuple.Create(i,s,false);
var foo = new [] { T(1, "x"), F(2, "y") };

Upvotes: 5

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174319

The shortest you can get is to use Tuple.Create instead of new Tuple:

var foo = new [] { Tuple.Create(1, "x", true), Tuple.Create(2, "y", false) };

Upvotes: 17

Related Questions