• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
shinypixel

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

8 posts in this topic

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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0