37

Let's say I have a class like this:

public class Fraction
{
   int numerator;
   int denominator;

   public Fraction(int n, int d)
   {
      // set the member variables
   }

   // And then a bunch of other methods
}

I want to initialize an array of them in a nice way, and this post is a big list of approaches that are error prone or syntactically cumbersome.

Of course an array constructor would be nice, but there's no such thing:

public Fraction[](params int[] numbers)

So I'm forced to use a method like

public static Fraction[] CreateArray(params int[] numbers)
{
    // Make an array and pull pairs of numbers for constructor calls
}

which is relatively clunky, but I don't see a way around it.

Both forms are error prone because a user could mistakenly pass an odd number of parameters, maybe because s/he skipped a value, which would leave the function scratching its head wondering what the user actually wanted. It could throw an exception, but then the user would need to try/catch. I'd rather not impose that on the user if possible. So let's enforce pairs.

public static Fraction[] CreateArray(params int[2][] pairs)

But you can't call this CreateArray in a nice way, like

Fraction.CreateArray({0,1}, {1,2}, {1,3}, {1,7}, {1,42});

You can't even do

public static Fraction[] CreateArray(int[2][] pairs)
// Then later...
int[2][] = {{0,1}, {1,2}, {1,3}, {1,7}, {1,42}};
Fraction.CreateArray(numDenArray);

Note that this would work just fine in C++ (I'm pretty sure).

You're forced to do one of the following instead, which is abhorrent. The syntax is terrible and it seems really awkward to use a jagged array when all the elements have the same length.

int[2][] fracArray = {new int[2]{0,1}, /*etc*/);
Fraction.CreateArray(fracArray);
// OR
Fraction.CreateArray(new int[2]{0,1}, /*etc*/);

Similarly, Python-style tuples are illegal and the C# version is icky:

Fraction.CreateArray(new Tuple<int,int>(0,1), /*etc*/);

The use of a pure 2D array might take the following form, but it's illegal, and I'm sure there's no legal way to express it:

public static Fraction[] CreateArray(int[2,] twoByXArray)
// Then later...
Fraction[] fracArray = 
    Fraction.CreateArray(new int[2,4]{{0,1}, {1,2}, {1,3}, {1,6}});

This doesn't enforce pairs:

public static Fraction[] CreateArray(int[,] twoByXArray)

OK, how about

public static Fraction[] CreateArray(int[] numerators, int[] denominators)

But then the two arrays might have different lengths. C++ allows

public static Fraction[] CreateArray<int N>(int[N] numerators, int[N] denominators)

but, well, this isn't C++, is it?

This sort of thing is illegal:

public static implicit operator Fraction[](params int[2][] pairs)

and unworkable anyway, again because of the abhorrent syntax:

Fraction[] fracArray = new Fraction[](new int[2]{0,1}, /*etc*/ );

This might be nice:

public static implicit operator Fraction(string s)
{
    // Parse the string into numerator and denominator with
    // delimiter '/'
}

Then you can do

string[] fracStrings = new string[] {"0/1", /*etc*/};
Fraction[] fracArray = new Fraction[fracStrings.Length];
int index = 0;
foreach (string fracString in fracStrings) {
    fracArray[index] = fracStrings[index];
}

I don't like this approach for five reasons. One, the implicit cast unavoidably instantiates a new object, but we already have a perfectly good one, namely the one we're trying to initialize. Two, it can be confusing to read. Three, it forces you to do explicitly what I wanted to encapsulate in the first place. Four, it leaves room for bad formatting. Five, it involves one-time parsing of string literals, which is more like a practical joke than good programming style.

The following also requires wasteful instantiation:

var fracArray = Array.ConvertAll(numDenArray, item => (Fraction)item);

The following use of a property has the same problem unless you use those terrible jagged arrays:

public int[2] pair {
    set {
        numerator = value[0];
        denominator = value[1];
    }
}
// Then later...
var fracStrings = new int[2,4] {{0,1}, /*etc*/};
var fracArray = new Fraction[fracStrings.Length];
int index = 0;
foreach (int[2,] fracString in fracStrings) {
    fracArray[index].pair = fracStrings[index];
}

This variation doesn't enforce pairs:

foreach (int[,] fracString in fracStrings) {
    fracArray[index].pair = fracStrings[index];
}

Again, this approach is big anyway.

These are all of the ideas I know how to derive. Is there a good solution?

1
  • 2
    There is a related post which proposes a trick using a list of objects. Commented Apr 20, 2016 at 7:29

3 Answers 3

40

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 } };
5
  • 1
    I like this for List<>! Commented Apr 20, 2016 at 7:49
  • 5
    Great solution! And memory-efficiency should be of no concern, if we are talking about hand written tuples in code! If there are more than 1000 they should be in a resource file!
    – Falco
    Commented Apr 20, 2016 at 11:41
  • Does this require a certain version of C#? I tried the new List<Fraction> { { 0, 1 }, { 1, 2 }, [...] example but it says Add doesn't take 2 arguments, although the extension is in scope. (Note: I'm not the asker)
    – George T
    Commented Apr 20, 2016 at 12:40
  • 5
    @GeorgeT: Add as an extension method like that requires C# 6. If you're stuck with an ancient version, you can always make an actual class that has Add as a normal method. That way you wouldn't have to use List<T> either which might have superfluous features for you, you could just make your own class which just implements IEnumerable and has an Add method which are the requirements for using the collection initializer syntax. Commented Apr 20, 2016 at 12:57
  • 1
    .NET Fiddle for @MattiVirkkunen's "ancient" approach: dotnetfiddle.net/SXlNKz
    – Sphinxxx
    Commented Apr 20, 2016 at 22:28
8

You could create a fraction array builder with a fluent interface. It would lead to something like

public class FractionArrayBuilder
{
  private readonly List<Fraction> _fractions = new List<Fraction>();

  public FractionArrayBuilder Add(int n, int d)
  {
    _fractions.Add(new Fraction(n, d));
    return this;
  }

  public Fraction[] Build()
  {
    return _fractions.ToArray();
  }
}

which can be called using

var fractionArray = new FractionArrayBuilder()
  .Add(1,2)
  .Add(3,4)
  .Add(3,1)
  .Build();

which is an easy to understand statement.

I have made a fiddle to demonstrate.

3
  • 1
    you could drop the first arg to the Add method and simply return this Commented Apr 20, 2016 at 16:02
  • 1
    This won't compile: if Add() is supposed to be an extension method, it needs to be static. But I don't see any reason why it shouldn't be just an instance method.
    – svick
    Commented Apr 20, 2016 at 16:54
  • you are both correct. I've edited. Commented Apr 21, 2016 at 7:59
7

The most succinct way I can think of for your particular example involves writing an implicit operator for the Fraction class:

public sealed class Fraction
{
    public Fraction(int n, int d)
    {
        Numerator   = n;
        Deniminator = d;
    }

    public int Numerator   { get; }
    public int Deniminator { get; }

    public static implicit operator Fraction(int[] data)
    {
        return new Fraction(data[0], data[1]);
    }
}

Then you can initialise it like this:

var fractions = new Fraction[]
{
    new [] {1, 2},
    new [] {3, 4},
    new [] {5, 6}
};

Unfortunately you still need the new [] on each line, so I don't think this gains very much over the normal array initialisation syntax:

var fractions = new []
{
    new Fraction(1, 2),
    new Fraction(3, 4),
    new Fraction(5, 6)
};

I suppose you could write a "local" Func<> with a short name to simplify the initialisation somewhat:

Func<int, int, Fraction> f = (x, y) => new Fraction(x, y);

var fractions = new []
{
    f(1, 2),
    f(3, 4),
    f(5, 6)
};

The drawback is that you'd need to add that extra line (initialising a Func<>) wherever you wanted to initialise the array - or have a private static method in the class instead - but then that method would be in scope throughout the class, which isn't ideal if it has a single-letter name.

However, the advantage of this approach is that it is very flexible.

I toyed with the idea of calling the inline function _, but I'm really not sure about that...

Func<int, int, Fraction> _ = (x, y) => new Fraction(x, y);

var fractions = new []
{
    _(1, 2),
    _(3, 4),
    _(5, 6)
};
3
  • Yeah, the syntax is better but still clunky. Besides, I would say it's error prone because the data parameter might not have two elements. In the worst case, it has only 0 or 1, which will throw an exception, and potential exceptions make a technique harder to implement. Commented Apr 20, 2016 at 7:39
  • 2
    Instead of a local Func, I would consider making it a public static method on some class, which you can access by using static.
    – svick
    Commented Apr 20, 2016 at 16:56
  • Great observations, I appreciate the all of your insight and explanations, I found the _ "underscore" comical.
    – Chef_Code
    Commented Sep 18, 2016 at 23:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.