Gergő Sz. Gergő Sz. - 3 months ago 14
C# Question

Declaration of a new class element

I have some problems with this code piece. I would appreciate some help.

class Alpha{
string Name;
public Alpha(string name){
this.Name = name;
}
}
class Beta{
Alpha[] alpha_array;
string Name;
public Beta(Alpha[] alpha_array, string name){
this.Alpha_array = alpha_array;
this.Name = name;
}
}

static void Main(){
Beta betas = new Beta[10];
for(int i = 0; i < betas.Length; i++){
betas[i] = new Beta(new Alpha[1], "Bob");
betas[i].alpha_array = new Alpha("George");
Console.WriteLine(betas[i].alpha_array.Name);
}
}


What is the problem here?
I would use this code but when I try to acces the alpha_array, the betas array doesn't have an alpha_array element. How to do this, I can't figure out it by myself.

Thanks for any help.

Answer

You have a few errors in your code:

All fields are private if you don't specify an access modifier. You should make them public. Example:

class Alpha{
  public string Name;
  public Alpha(string name){
    this.Name = name;
  }
}

class Beta{
  public Alpha[] alpha_array;
  public string Name;
  public Beta(Alpha[] alpha_array, string name){
    this.Alpha_array = alpha_array;
    this.Name = name;
  }
}

You're trying to assign an instance of Alpha to an Array of Alpha:

betas[i].alpha_array = new Alpha("George");

I think what you want is the following:

for(int i = 0; i < betas.Length; i++){
    betas[i] = new Beta(new Alpha[]{ new Alpha("George")}, "Bob");
    Console.WriteLine(betas[i].alpha_array[0].Name); // prints George
}
Comments