开发者

Initializing lists in a constructor

开发者 https://www.devze.com 2022-12-24 06:46 出处:网络
I need to create a class that also initializes two event lists to new empty lists. I\'m not sure if that is what is being asked of me, 开发者_运维技巧but I know how to create a list and how to create

I need to create a class that also initializes two event lists to new empty lists. I'm not sure if that is what is being asked of me, 开发者_运维技巧but I know how to create a list and how to create a constructor. I created 2 lists, and now I should create the constructor. Here is one of my lists:

List<Person> organize = new List<Person>();

How do I initialize the two event lists in the constructor to new lists?


Based on what I can gather from your question, you have a class with two Lists.

Your requirements say that inside your class, you need to initialize the Lists to empty lists.

Below is the example (the only difference is that I never initialize the Lists when they declared, but in the class constructor instead):

public class YourClass
{
    List<Person> organize;
    List<Person> anotherOrganize;

    // constructor
    public YourClass()
    {
        // initialize the two lists to empty lists
        organize = new List<Person>();
        anotherOrganize = new List<Person>();
    }
}


If your list is declared as a field (member variable directly inside the class) and it's initialized at its declaration, you shouldn't to reinitialize it in the constructor. The initialization expression will get moved to the constructor by the compiler automatically.


If this is homework, your instructor is probably telling you to initialize the lists inside of the constructor instead of at the declaration point.

class MyClass
{
    List<Person> organize;

    public MyClass()
    {
        this.organize = new List<Person>();
    }
}


List<Person> organize = new List<Person>();

This will create an empty list. Can you be more specific? I feel like some details are missing.

Perhaps you mean something like this?

 public class TestClass
 {
      List<Person> personList;

      public TestClass()
      {
           personList = new List<Person>();
      }

 }


I think what you're asking is why the constructor to your class should instantiate the two lists (?). You're right that

List<Person> organize = new List<Person>();

will instantiate the list. But so will:

List<Person> organize;
public MyClass()
{
organize = new List<Person>();
}

Am I understanding the question?

0

精彩评论

暂无评论...
验证码 换一张
取 消