'How to avoid instantiating an object every single time so I can add objects to a list of objects contained within that first object?
Each time I click on a button I would like to add a new location via the AddLocation method to a list of LocationSpecs objects. But with the code as is, a new officeRental object is created every time I click on the btnAddLocation button with a new list of LocationSpecs objects. So every time I click on the button the previous object is lost from memory. How can I modify this code so in the end I can have only one list of LocationSpecs objects inside a single officeRental object?
private void btnAddLocation_Click(object sender, EventArgs e) { string name = txtName.Text; string neighborhood = txtNeighborhood.Text; LocationSpecs location = new LocationSpecs(name, neighborhood); OfficeRental officeRental = new OfficeRental(); officeRental.AddLocation(location); MessageBox.Show(name + " in " + neighborhood + " added."); }
public class OfficeRental : IOfficeRental { public List<LocationSpecs> LocationSpecs { get; set; } public OfficeRental() { LocationSpecs = new List<LocationSpecs>(); } public void AddLocation(LocationSpecs locationSpecs) { // throw new NotImplementedException(); LocationSpecs.Add(locationSpecs); }
public class LocationSpecs { public string Name { get; } public string Neighborhood { get; } public LocationSpecs(string name, string neighborhood) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException(nameof(name)); if (string.IsNullOrWhiteSpace(neighborhood)) throw new >ArgumentException(nameof(neighborhood)); Name = name; Neighborhood = neighborhood; }}
Solution 1:[1]
You should move the line:
OfficeRental officeRental = new OfficeRental();
from the button click function and make it a Class member variable, similar to:
class <yourFormName>
{
OfficeRental officeRental = new OfficeRental();
... // the rest of your code
}
This will mean that the officeRental object is now visible throughout the whole class (a class member variable) instead of just being used in the single button click handler.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JayV |
