Wednesday, March 15, 2006

Static properties and derived classes in .NET

So I find yet another "weird-one" in .NET. In the past I've used a base class for logging that has several static properties that I configure for the derived class (one of these is the log file location) and then a set of static methods that I can then use to log messages (such as debugging information to file). From this I then derive a new class that sets the necessary bits depending upon what the application needs to do (it may not have mail logging for instance).

Until now I've only ever had one of these logging classes in a project but today I'm working on a project that actually needs two (log messages for different parts of the application go to different files).

So I've got two classes that derive from the same base class each to configure the base class (it's static properties) as required. But guess what - you can't. Because they're static properties .NET makes the base class for both derived classes the same class.

So whereas what I want is:

CLASS1 derived from BASE1 with LogFile set to e:\temp\downloads.log
CLASS2 derived from BASE2 with LogFile set to e:\temp\tickets.log

What I actually have is CLASS1 and CLASS2 derived from the same BASE class with LogFile set to whichever class was initialized last (which in this case is CLASS2).

Now I know this may not be the best architecture to have (and I've now had to change it so that it works) but surely both classes should have different base classes?

No comments: