I have several instances of a class. Each instance stores data in a common database. So, I thought “I’ll make the DataTable table
field static, that way every instance can just add/modify rows to its own table
field, but all the data will actually be in one place!”
However, apparently it’s a bad idea to do use static fields, especially if it’s databases: Don’t Use “Static” in C#?
Is this a bad idea? Will I run into problems later on if I use it?
This is a small project so I can accept no testing as a compromise if that is the only drawback. The benefit of using a static database is that there can be many objects of type MyClass
, but only one table they all talk to, so a static field seems to be an implementation of exactly this, while keeping syntax concise.
I don’t see why I shouldn’t use a static field (although I wouldn’t really know) but if I had to, the best alternative I can think of is creating one DataTable
, and passing a reference to it when creating each instance of MyClass
, perhaps as a constructor parameter.
But is this really an improvement? It seems less intuitive than a static field.
3
You wouldn’t get any improvement if you pass an instance of the DataTable
to each instance of MyClass
, you still have a single DataTable
instance every object refer to, and will use a bit more memory because each object will have that instance unlike a static field that is a single reference for the hole class.
For the first view, you shouldn’t have any problems using this architecture, the problems can rise if you have multithreading and concurrent acesses to the DataTable
.
5
Reading DataTable
across multiple threads should be OK . Writing is not, you should synchronize write access. See “Thread Safety” in Data Table doc.
Might need to create a separate object that deals with data access and synchronization.
At the most basic though, you could just call lock(table) {//Write here}
before you write the data in every thread.
Now, you shouldn’t need to have a static variable to have it shared between instances, you could just set every thread to reference the same instance. This will give you more flexibility going forward (For example: to improve write performance you can have multiple connections and you can assign them from the pool every time a new thread is created)