demented hedgehog
demented hedgehog

Reputation: 7538

C# Overloaded constructor cannot differ on use of parameter modifiers only

I get the compiler error in the title with an error ID of CS0851 when I try and do this:

public class Cells {

    public Cells(params Cell[] cells) : this(cells) {}

    public Cells(Cell[] cells) { ... }
}

I know I can get around this by getting rid of the first constructor and requiring code to use the later constructor (forcing the conversion to an array where the constructor is being called) but I think that's not a nice outcome. I understand why the compiler might have problems differentiating between the constructors with these similar signatures.

The question is: Is there some way I can actually get this to work?

   Cells c1 = new Cells(new Cell[] { new Cell(1), new Cell(2)});
   Cells c2 = new Cells(new Cell(4), new Cell(5));

This is using mono and is possibly a newbie question.

Upvotes: 2

Views: 162

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

You can pass both single items and arrays using the params constructor, you don't need two constructors.

using System;

public class Cell
{
    public Cell(int x) {}
}

public class Cells
{
    public Cells(params Cell[] cells) { Console.WriteLine("Called with " + cells.Length.ToString() + " elements"); }
}

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Write("Test #1: ");
           Cells c1 = new Cells(new Cell[] { new Cell(1), new Cell(2)});
            Console.Write("Test #2: ");
           Cells c2 = new Cells(new Cell(4), new Cell(5));
        }
    }
}

Run Code

Upvotes: 7

SonneXo
SonneXo

Reputation: 177

How about a static constructor for your second case?

public class Cells
{
    public Cells(Cell[] cells)
    {

    }

    public static Cells getCells(params Cell[] cells)
    {
        return new Cells(cells);
    }
}

Its the simplest way I see.

Upvotes: 0

Related Questions