0

Well I have a class like this and I want to store in a list which is defined as a static variable. I was following the reference here: Storing data into list with class

public class Faculty
{
    public string Name { get; set; }
    public string Dept { get; set; }
    public string[] subInterest = new string[4];
}

However when I try to initialize the list as follows I have problem with the array part: Invalid initializer member declarator

SaveDirectory.list_of_faculty.Add(
    new Faculty
    {
        Name = txtTeachherName.Text,
        Dept = cmbDepts.Items.CurrentItem.ToString(),
        subInterest[0] = "HELLO"
    });

What am I doing wrong?

Community
  • 1
  • 1
Jishan
  • 1,592
  • 3
  • 24
  • 57

3 Answers3

2

You can't reach in to your object and initialize members of an array that it holds using initializer syntax. You could work around this as follows:

var fac = new Faculty {
     Name = txtTeachherName.Text, 
     Dept = cmbDepts.Items.CurrentItem.ToString(), 
     subInterest = new []{"HELLO", null, null, null}}

or after initialization:

fac.subInterest[0] = "HELLO";
spender
  • 112,247
  • 30
  • 221
  • 334
0

The problem is due to:

subInterest[0] = "HELLO"

You can not partially initialize an array in Object Initializer, either it is full or nothing, You can do:

subInterest = new string[]{"HELLO"}

But, this will leave the array subInterest with size 1, not as size 4, as you have defined in your class. To get the array of same size you can do:

subInterest = new string[]{"HELLO",null,null,null}

Another option is to use List<string> instead of an Array. You can initialize it with value and later you can add items to it.

Modify your class like:

public class Faculty
{
    public string Name { get; set; }
    public string Dept { get; set; }
    public List<string> subInterest;
}

and then:

new Faculty
{
    Name = txtTeachherName.Text,
    Dept = cmbDepts.Items.CurrentItem.ToString(),
    subInterest = new List<string>(){"HELLO"}
};
Habib
  • 212,447
  • 27
  • 392
  • 421
0

Using a constructor can also solve the problem like

public class Faculty
{
    public string Name { get; set; }
    public string Dept { get; set; }
    public string[] subInterest = new string[4];

    public Faculty(string name, string dept, string[] si)
    {
        this.Name = name;
        this.Dept = dept;
        this.subInterest = si;
    }
}

Then instantiate the faculty class

string[] subinterest = new string[]{"reading","swmming",null,null};
var fac = new Faculty("dgdfgdfgfg","dfgdgfgdfg", subinterest);
Rahul
  • 73,987
  • 13
  • 62
  • 116