Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# multidimensional immutable array

I need to create a field for simple game. In first version the field was like Point[,] - two dimensional array.

Now i need use System.Collections.Immutable (it's important condition). I trying to google and can't find anything, that can help me. I don't understand how i can create two-dimensional ImmutableArray (or ImmutableList)?

like image 763
murzagurskiy Avatar asked Sep 19 '15 14:09

murzagurskiy


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

There isn't the equivalent of a rectangular array as far as I'm aware, but you could:

  • Have an ImmutableList<ImmutableList<Point>>
  • Wrap a single ImmutableList<Point> in your own class to provide access across two dimensions.

The latter would be something like:

// TODO: Implement interfaces if you want
public class ImmutableRectangularList<T>
{
    private readonly int Width { get; }
    private readonly int Height { get; }
    private readonly IImmutableList<T> list;

    public ImmutableRectangularList(IImmutableList<T> list, int width, int height)
    {
        // TODO: Validation of list != null, height >= 0, width >= 0
        if (list.Count != width * height)
        {
            throw new ArgumentException("...");
        }
        Width = width;
        Height = height;
        this.list = list;
    }

    public T this[int x, int y]
    {
        get
        {
            if (x < 0 || x >= width)
            {
                throw new ArgumentOutOfRangeException(...);
            }
            if (y < 0 || y >= height)
            {
                throw new ArgumentOutOfRangeException(...);
            }
            return list[y * width + x];
        }
    }
}
like image 197
Jon Skeet Avatar answered Oct 28 '22 04:10

Jon Skeet