Question

Just a very quick question. I have a classe called "Mezo.cs" that is basically a 'public int[,]'. A specific copy of this class is a int[,] containing 1 or 0. I want to find the 1s. So in the main program I iterate through it with fors but i get the error in the title. Any help would be appreciated.

static void WriteShips(Mezo mezo, StreamWriter SW)
    {
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                if (mezo[i, j] == 1)
                {
                    SW.WriteLine(i.ToString(), j.ToString());
                }

            }
        }

    }

This is in a battleship program where I want to basically want to save the coordinates of the ships in a txt. mezo[i, j] gives the error

MEZO CLASS:

class Mezo
{
    public int[,] mezo;

    public Mezo()                            // KONSTRUKTOR
    {
        mezo = new int[10, 10];        
        kitoltesUressel();          


    }

kitoltesUressel() is irrelevant, it just randomly fills the copy with 1s and 0s.

Was it helpful?

Solution

In order to use an instance of your class with indexes (pretty much like any collection in the framework), you need to have a property that will act like the index manager.

Here is a simple code of a class that behaves like an array:

public class MyIndexedClass
{
    private string[] _values = new string[]
    {
        "hello",
        "hi",
        "good morning",
        "long time no see"
    };
    public string this[int index]
    {
        get
        {
            Console.WriteLine("Index called with argument value " + index);
            return _values[index];
        }
        set
        {
            Console.WriteLine("Index called with argument value " + index + " and value " + value );
            _values[index] = value;
        }
    }
}

In my example, using the code myIndexedClassInstance[0]; returns a string containing "hello".

I'm guessing your "Mezo" class contains a jagged array inside of it, but not using the "this" keyword.

You can check more about indexes here.

EDIT:

Updated now given the new info about your Mezo class, the code that is giving you the error should look like this:

if (mezo.mezo[i, j] == 1)
{
   SW.WriteLine(i.ToString(), j.ToString());
}

Because you are passing an instance of Mezo, which is the one containing the array called mezo. You cannot use the instance of the class itself as if it was the jagged array property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top