C# Static Access – Static DataTable or DataSet in a Class: Bad Idea?

ado.netcstatic-access

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.

Best Answer

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.

Related Topic