Elegant initialization of an array of class instances in C# [closed]

I can’t think of an elegant, and at the same time memory efficient solution for array.

But there is an elegant solution for list (and similar) utilizing the C# 6 collection initializer feature:

public static class Extensions
{
    public static void Add(this ICollection<Fraction> target, int numerator, int denominator)
    {
        target.Add(new Fraction(numerator, denominator));
    }
}

With that extension method in place, you can easily initialize a Fraction list for instance:

var list = new List<Fraction> { { 0, 1 }, { 1, 2 }, { 1, 3 }, { 1, 7 }, { 1, 42 } };

And of course, although not memory efficient, you can use it to initialize Fraction array either:

var array = new List<Fraction> { { 0, 1 }, { 1, 2 }, { 1, 3 }, { 1, 7 }, { 1, 42 } }.ToArray();

or even making it more concise by declaring a list derived class with implicit array conversion operator:

public class FractionList : List<Fraction>
{
    public static implicit operator Fraction[](FractionList x) => x?.ToArray();
}

and then use

Fraction[] array = new FractionList { { 0, 1 }, { 1, 2 }, { 1, 3 }, { 1, 7 }, { 1, 42 } };

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)