0

could anyone give me a helping hand with class declaration in another class or just tell me, what could be wrong?

I have 2 classes:

public class alfa
{
    int color = "";
    public int y=0;

    public int getY()
    {
        return y;
    }
    public void setColor(string x)
    {
        color = x;
    }    
}

public class beta
    {
        int size = 10;
        public alfa[] alfaB = new alfa[size / 2];
        
        for (int i = 0; i < size/2; i++)
            {
                alfaB[i].setColor("b");
                alfaB[i].y = 0;
            } 
    }

Syntax check in IDE shows no error, but there is something wrong in runtime. In class Beta Visual Studio offers me all functions of alfaB (y variable, setColor method) but in runtime I see error System.NullReferenceException: The object reference is not set to an object instance. It seems there is no access to alfa class but I have no idea why.

Any advice?

Martin
  • 21
  • 1
  • 4
  • 3
    `alfaB` is an empty car park and you're trying to take the car that's (not) in space 0 and drive it. That is: you have space for `size / 2` elements, but you don't have anything in the spaces. You need to initialize each position (e.g. `alfaB[i] = new alfa();`). – ProgrammingLlama Jun 28 '21 at 06:18
  • 1
    no compile error, just runtime error --- this is no strange, just too common. – Lei Yang Jun 28 '21 at 06:18
  • 2
    `beta` is invalid syntax. Can't have a for loop outside a method/property – Hayden Jun 28 '21 at 06:18
  • As a side-note, I strongly recommend that you learn about and start following C# and .NET naming conventions, and learn about properties instead of "get" and "set" methods. (Also, the code you've provided for `beta` wouldn't compile, as you can't put a `for` loop directly in a class declaration like that.) – Jon Skeet Jun 28 '21 at 06:18
  • There's no way this would compile either ... `int color = ""` won't compile, also, there's a `for` loop directly in the `beta` class instead of inside a method _in_ that class, ... So, seems to me you either gave us only part of the code - or your IDE is seriously corrupted :) – Nsevens Jun 28 '21 at 06:19
  • I am totally dumb. Of course, loop has to be inside of function... But primary error is fixed by Llama advise. Thanks! – Martin Jun 28 '21 at 06:29

0 Answers0