C# – How to Store Data Accessible to Other Classes

cclassstatic

I'm writing a CAD program. Let's say I have in input class, this class reads various data from a text file and creates lots of lists/dictionaries and …. These data need to be accessed by other methods in other classes to be modified. Now here is how I have done it so far:

I have one static class: Building.cs When I create/or load a project this class holds all the data like list of columns, beams, points, etc. All of these are stored as private fields. I can access these using the class's public methods like GetColumns or GetPoints …

Now I also have non-static classes. They contain 2-3 public methods. and do some stuff on various parts of the building.

public static class Building
{
    private static List<Column> columns;
    private static List<Beams> beams;
    private static List<Points> points;

    public static List<Column> GetColumns() 
    {
        return Columns;
    }
}

public class ColumnsService()
{
    private List<Columns> columns;
    public GroupColumns(List<Columns> columns)
    {
        this.columns = columns;
    }

    public void Group()
    {
        // group columns
    }
}

var columns = Building.GetColumns();
var columnsService = new ColumnsService(columns);
columnsService.Group();

I was wondering is this the way to go? How else can I store the data. The data needs to be accessible throughout the lifetime of the program to most of the classes.

Best Answer

Because in your first question you professed a lack of knowledge about dependency injection, I will explain it in simple terms:

public class ThingThatNeedsABuilding
{
  private Building building;
  public ThingThatNeedsABuilding(Building building)
  {
    this.building = building;
  }
}

public class OtherThingThatNeedsABuilding
{
  private Building building;
  public OtherThingThatNeedsABuilding(Building building)
  {
    this.building = building;
  }
}

public class Application
{
  public static void Main(string[] args)
  {
    var building = new Building();
    var thing1 = new ThingThatNeedsABuilding(building);
    var thing2 = new OtherThingThatNeedsABuilding(building);
  }
}

It's really that simple. The same instance of building is now shared between those two instances and nothing else. This is important. You do not want more stuff than needed to be available. This helps you avoid it.

If an object needs something, by all means give that something to it. Making it globally accessible to all objects makes it hard to tell if your program will even run, because an issue in the configuration of the dependency may cause a crash, but you can't tell at initialization that an object even has that dependency.

There are other important reasons to inject dependencies, but that one is very simple to understand and very hard to reject.