Passing List between C# Forms

I am trying to learn passing a list between two C# forms using constructors as shown below. On the first form I did:

List<Cat> myCatList;
//list populating function...
private void btnDisplay_Click(object sender, EventArgs e)
 {
    df = new DisplayForm(myCatList);   
    df.Show();
    this.Hide();
 }

On the next form, I tried to receive the data as shown below:

List<Cat> catList; 
public DisplayForm(List<Cat> catList)
  {
     InitializeComponent();
     this.catList = catList;
  }

But I always get an error on the second form constructor saying:

Error 1 Inconsistent accessibility: parameter type 'System.Collections.Generic.List<_05_WindowsFormsAppCat.Cat>' is less accessible than method '_05_WindowsFormsAppCat.DisplayForm.DisplayForm(System.Collections.Generic.List<_05_WindowsFormsAppCat.Cat>)'

Any ideas?

Jon Skeet
people
quotationmark

The List part is a complete red herring here. You'd get exactly the same problem if your constructor had a Cat parameter instead of a List<Cat> parameter.

Your Cat type is probably internal, because you haven't declared it as public. Therefore you can't use it in the signature of a public member such as this:

public DisplayForm(List<Cat> catList)

Options:

  • Make Cat a public class
  • Make your DisplayForm constructor internal

Personally I'm all for keeping things as private as is practical - although for small projects it won't make much difference, particularly for apps which are just a single assembly anyway. Most developers tend to err on the side of making everything public, which is a mistake IMO, but it's a judgement call. Both of the above options will work fine... but you should at least think about whether you want any other assembly to know about the Cat type (or indeed whether you want code in other assemblies to be able to call that constructor).

people

See more on this question at Stackoverflow