List in Class

AussieBoy

Well-known member
Joined
Sep 7, 2020
Messages
78
Programming Experience
Beginner
Hi, how do I populate a list with in a class.
So that there elements with in it when it is created.
C#:

class AClass
{
private List<ListModel> ListModellist = new List<ListModel>();
}

Name = "NameTest",
Description = "DescriptionTest",
Date = DateTime.Now
//etc

Thanks,
 
Last edited:
All lists are within a class. There's nothing different about this one. If you have previously created WinForms projects then each of your forms is a class, so any lists you created in a form are within a class.

Anyway, you have two choices for adding items to that list. You can do it when you create the list object, e.g.
C#:
class AClass
{
    private List<ListModel> ListModellist = new List<ListModel> { new ListModel(), new ListModel() };
}
Alternatively, as with any class, you can add code to the constructor to be executed when an instance is created:
C#:
class AClass
{
    private List<ListModel> ListModellist = new List<ListModel>();

    public AClass()
    {
        ListModellist.Add(new ListModel());
        ListModellist.Add(new ListModel());
    }
}
 
When you create an instance of that class, that object will occupy memory on the managed heap. As long as you have a variable that refers to that object, the object will continue to exist. Once the last reference to that object falls out of scope, e.g. a local variable declared in a method that completes executing, then that memory becomes eligible for garbage collection. The object will continue to exist in memory but you can't access it. When the system decides that it needs the memory and/or it has time to reclaim it, the object will cease to exist. That will remove the last reference to the list within that object, so that memory also becomes eligible for cleanup. That may happen immediately or not. It's really up to the garbage collector and I don't know all the specific details of how that's implemented. One of the points of .NET is that you don't have to know or care about deallocating memory. You just have to follow a few simple rules and the system will take care of the rest.

If it is important to you that the list be cleaned up immediately that you finish using the object, you should implement the IDisposable interface in your class and then you can do whatever is required to clean up the object in the Dispose method. The object will still exist after its disposal and will still rely on the garbage collector to clean up its memory, but you get to decide what happens to the data/memory within the object at the moment its usefulness ends.
 

Latest posts

Back
Top Bottom