Jump to content

  • Log In with Google      Sign In   
  • Create Account


How to return a reference of type Array2D in C#?

  • You cannot reply to this topic
8 replies to this topic

#1 shinypixel   Members   -  Reputation: 137

Like
0Likes
Like

Posted 05 June 2014 - 05:29 PM

Once upon a time, I had this in C++:

template <typename T>
class Array2D
{
    // ...
    T& get(const int x, const int y)
    {
        return m_array[y * m_width + x];
    }
}

I was using a 2D array to have a type of DLinkedList. Each cell in a map would have a linked list.

 

Well, now I'm trying to covert that into C#.

        public T Get(int x, int y)
        {
            return m_array[y * m_width + x];
        }

The problem is it's not returning a reference as previous done in C++, but rather a value.

 

So, I can't do something like this...

            map = new Array2D<List<int>>(10, 10);

            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    map.Get(x, y).Add(0);
                }
            }

Even if I use the Set() method, adding 0 to the end of the list is trying to set an integer value of type List. So that doesn't work.

 

I tried using unsafe code with pointers, but the compiler yelled at me for trying it on a managed type of T.

 

Overloading [,] is not available.

 

I feel I'm missing something very obvious to do, but I can't grasp it. Any thoughts? Thank you.


Edited by shinypixel, 05 June 2014 - 05:39 PM.


Sponsor:

#2 DvDmanDT   Members   -  Reputation: 784

Like
0Likes
Like

Posted 05 June 2014 - 05:54 PM

In C# this depends on whether or not T (the tempate/generic type) is a struct/value type or a class/reference type. For example, int, float and Point are value types which are never returned by reference while other types declared with the class keyword will always be returned by reference. There is no way to return a value type (struct) as a reference in C#. It's by design.

 

Edit: I didn't read this through. Your example should work since List<T> is a generic reference type. 0 should be added to the list at coords (x, y). If not, please share your exceptions and/or compiler errors.

 

Edit2: Also, why isn't overloading of [,] available? Not that it'd make a difference since it would behave exactly like that Get method, but you can do it.

public T this[int x, int y] {
   get
   {
      return m_array[y * m_width + x];
   }
}



 

Edit3: (yes I'm drunk) You did initialize those lists right?

Set(x, y, new List<int>());

...

public void Set(int x, int y, T val)
{
   n_array[y * m_width + x] = val;
}



Edited by DvDmanDT, 05 June 2014 - 06:04 PM.


#3 shinypixel   Members   -  Reputation: 137

Like
0Likes
Like

Posted 05 June 2014 - 06:24 PM

No exceptions. Maybe I'm drunk and didn't know it. It must be another bug then.



#4 Nypyren   Crossbones+   -  Reputation: 3693

Like
0Likes
Like

Posted 05 June 2014 - 06:57 PM

Is this what you want?
 
using System.Collections.Generic;

namespace AutoGrid
{
    public class SparseListGrid<T>
    {
        List<T>[,] data;

        public SparseListGrid(int width, int height)
        {
            data = new List<T>[width, height];
        }

        public List<T> this[int x, int y]
        {
            get
            {
                var list = data[x,y];

                if (list == null)
                    data[x,y] = list = new List<T>();

                return list;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var grid = new SparseListGrid<int>(20, 20);

            grid[10,10].Add(100);
            grid[10,10].Add(150);
        }
    }
}
NOTE: If you don't want to be forced to use List<T>, you can tweak the code slightly to be more like your original pattern.
 
using System.Collections.Generic;

namespace AutoGrid
{
    public class AutoGrid<T> where T : new()
    {
        T[,] data;

        public AutoGrid(int width, int height)
        {
            data = new T[width, height];
        }

        public T this[int x, int y]
        {
            get
            {
                var element = data[x,y];

                if (element == null) // NOTE: this line is always false for value types.
                    data[x,y] = element = new T();

                return element;
            }

            set
            {
                data[x,y] = value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var grid = new AutoGrid<List<int>>(20, 20);

            grid[10,10].Add(100);
            grid[10,10].Add(150);
        }
    }
}

Edited by Nypyren, 05 June 2014 - 07:17 PM.


#5 shinypixel   Members   -  Reputation: 137

Like
0Likes
Like

Posted 05 June 2014 - 07:21 PM

Edit: Hmm... gotta think.

 

Well, the problem is the linked list is null on each element. I figured Add() allocates a node like my old code did.

 

First for loop set does add to the list now.  0 is added for map(0,0) with a count of 1.

 

The second reads the node at map(0,0) but it is null, which is confusing to me.

 

           map = new Array2D<List<int>>(10, 10);

            // set grid with 1 node of value 0.
            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    var val = map.Get(x, y);
                    val = new List<int>();

                    val.Add(0);
                }
            }

            // read the nodes
            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    var lst = map.Get(x, y);

                    foreach (int i in lst)
                    {
                        wl(i.ToString(), Color.White);
                    }
                }
            }

Edited by shinypixel, 05 June 2014 - 07:34 PM.


#6 phil_t   Crossbones+   -  Reputation: 3203

Like
0Likes
Like

Posted 05 June 2014 - 07:31 PM

You can't return a ref from a method in C#, the language doesn't allow it. It's not a problem for reference types (classes) of course, but it is for value types (structs). So that means if you have a wrapper over an array of value types, you can only return copies of the elements in the array, not references to the individual elements. Yeah, it sucks.



#7 shinypixel   Members   -  Reputation: 137

Like
0Likes
Like

Posted 05 June 2014 - 07:40 PM

Hmm,

 

Array2D is a class.

List is a class.

 

I wonder if it's List<int> then, since int is not a reference type.

 

I'm assuming it will work fine then with class types then: List<Cell> etc.

 

Array2D<List<Cell>> does the same thing.. I'm going insane.

     Array2D<List<Cell>> map;
            map = new Array2D<List<Cell>>(10, 10);

            // set grid with 1 node of value 0.
            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    var val = map.Get(x, y);
                    val = new List<Cell>();
                    // yay, it adds
                    val.Add(new Cell(0));
                }
            }

            // read the nodes
            for (int y = 0; y < map.Height; y++)
            {
                for (int x = 0; x < map.Width; x++)
                {
                    var lst = map.Get(x, y); // null list

                    foreach (Cell c in lst)
                    {
                        wl(c.type.ToString(), Color.White);
                    }
                }
            }

After adding Cell(0), the map object remains to have index 0 null. It feels like it's still acting the same even though they are all classes this time.


Edited by shinypixel, 05 June 2014 - 08:05 PM.


#8 phil_t   Crossbones+   -  Reputation: 3203

Like
0Likes
Like

Posted 05 June 2014 - 08:15 PM

That's because you're adding Cell(0) to a new List<Cell> that you created, not to the one that (maybe) already exists in your Array2D at (x,y).

 

Instead, allocate the new List<Cell> in the map.Get function, if the one at that spot is null.



#9 shinypixel   Members   -  Reputation: 137

Like
0Likes
Like

Posted 05 June 2014 - 08:49 PM

Okay, that worked.

 

What's new is I added this with the new restricter:

  class Array2D<T> where T : new()

I modified the Get() method:

        public T Get(int x, int y)
        {
            var val = m_array[y * m_width + x];

            if (val == null)
                m_array[y * m_width + x] = val = new T();

            return val;
        }

Then I added a new cell as such:

 map.Get(x, y).Add(new Cell(0));

Thanks for the help.


Edited by shinypixel, 05 June 2014 - 08:52 PM.






PARTNERS