0

I am trying to create an array of objects from Person objects in Employee class but I am getting these errors:

CS0270 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

CS1519 Invalid token '.' in class, struct, or interface member declaration CS1519

Invalid token '=' in class, struct, or interface member declaration

    void Main()
    {
    
    }
    
    public class Person{
        public string Name{ get; set;}
    }
    public class Employee{
        Person[] persons = new Person[3];
        persons[0].Name = "Ali";
    }

What am I doing wrong?

3
  • 3
    persons[0].Name = "Ali"; needs to be inside a method Commented Apr 20, 2017 at 21:17
  • Thanks Jonesopolis but can I ask you why? Commented Apr 20, 2017 at 21:21
  • @Behseini, that is how c# was designed. Contrary to, let's say PHP, you have to organize your code certain way. Commented Apr 21, 2017 at 7:14

1 Answer 1

3

Assigning value to persons array's first element cannot be done this way. You have to do it inside method or constructor. Something like this:

public class Employee
{
    Person[] persons = new Person[3];

    //through constructor
    public Employee()
    {
        persons[0].Name = "Ali";
    }

    //method that takes index and name
    public void AddPerson(int index, string name)
    {
        persons[index].Name = name;
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

+1 but the function does not have anything to prevent the user from inputting an index higher than what the array can support.
Thanks a lot Nino but can you please also let me know what is the logic behind this?
@JohnOdom that is true, but this is only an example, that shows basic usage.
@Behseini take a look at documentation that explains classes and structs
@Behseini, check the index and compare with length of array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.