7

I'm trying to initialize an immutable list like a regular list, but it's telling me it doesn't take 0 arguments. It throws the same error if I pass 1 argument, 2 arguments, etc.

public static readonly ImmutableList<object[]> AddressTestCases = new ImmutableList<object[]>
{
    new object[]{ "", false },
    new object[]{ "testestest", true },
};

What am I doing wrong here? Is there a way to do this without using .Add?

Gyn Manstot
  • 183
  • 2
  • 9
  • What you're doing wrong is using a constructor that doesn't exist. Pass the set of objects you want in the list to the constructor. – JSteward Jun 12 '18 at 15:07
  • If the constructor doesn't exist, how do you pass a set of object to it? It doesn't work with 1 argument, 2, etc. either. It throws the same error. – Gyn Manstot Jun 12 '18 at 15:09
  • Like the error states, `ImmutableList does not contain a constructor that takes 0 arguments`. You need to use the constructor that takes one argument, i.e. the one that takes a list of objects. – JSteward Jun 12 '18 at 15:10
  • `ImmutableList does not contain a constructor that takes 1 arguments` Then I get this error, I tried just passing `null` – Gyn Manstot Jun 12 '18 at 15:12

3 Answers3

9

Ok ImmutableList has a create method that you should be using

public ImmutableList<int> ImmutableListCreate()
{
    return ImmutableList.Create<int>(1, 2, 3, 4, 5);
}
JSteward
  • 6,833
  • 2
  • 21
  • 30
0

To create an ImmutableList you have to use the static factory method Create() defined on the ImmutableList static class.

This means you will need

public static readonly ImmutableList<object[]> AddressTestCases = 
    ImmutableList.Create(new object[] { "", false }, new object[] { "testtest", true });
Cosmin Sontu
  • 1,034
  • 11
  • 16
-1

The syntax you are using is not calling the constructor you think it is. It is calling the empty constructor and then n the background calling .Add for the object arrays you gave.

You will need to use one of the builder methods:

public static readonly ImmutableList<object[]> AddressTestCases =
                          new[] {
                                   new object[]{ "", false }, 
                                   new object[]{ "testestest", true }
                                }).ToImmutableList();
nvoigt
  • 75,013
  • 26
  • 93
  • 142