bml
bml

Reputation: 59

Instantiating lists correctly

Sorry if this is a bit of a silly question but I think I'm misunderstanding something basic about Lists and Goggling hasn't helped. This is what I have:

A class containing List elements:

public string Name { get; set; }
public int Age { get; set; }
public List<int> Main_Spec { get; set; }
public List<int> Aux_Spec { get; set; }

public Department()
{
    List<int> Main_Spec = new List<int>();
    List<int> Aux_Spec = new List<int>();
}

I then try to add elements to Main_Spec as follows:

Department departnment = new Department();
List<int> inter = new List<int>();

var parts2 = parts[2].Split(',');
foreach (string part in parts2)
{
   inter.Add(int.Parse(part));
}
departnment.Main_Spec = inter;
inter.Clear();

I use the intermediate list because when I tried to add straight to department.Main_Spec I got an error saying that the object isn't instantiated (or something along those lines). My Problem is that looking at it in debugging mode, when I clear inter, department.Main_Spec also gets cleared. That's not what I'm trying to achieve and I don't really understand why it's doing that.

Thank you in advance!

Upvotes: 0

Views: 75

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107606

You just have a small mistake in your constructor. You should define the local properties of the class instead of trying to declare and define new ones (local to the constructor):

public Department()
{
    this.Main_Spec = new List<int>();
    this.Aux_Spec = new List<int>();
}

Now you can go back to the original way of not using an intermediate class. For example:

Department departnment = new Department();
department.Main_Spec.AddRange(parts[2].Split(',').Select(p => int.Parse(p));

Here I also avoided using the for-loop with AddRange().

Upvotes: 5

mason
mason

Reputation: 32719

Change your constructor to this:

public Department()
{
    Main_Spec = new List<int>();
    Aux_Spec = new List<int>();
}

You were using local (function level) variables instead of referring to the class level variables.

Upvotes: 3

Related Questions