Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared functionality between C# console apps

I have two console apps, Query and Update, that share some functionality. I wanted to have the two classes inherit from a common base class, but the problem is that, for a console app, I have to have a static Main function. What I currently have is the following:

namespace Utils
{
    public class ConsoleBase
    {
        protected const int ERROR_EXIT_CODE = 1;
        protected static void printWarning(string msg) {...}
        public ConsoleBase(IEnumerable<string> args) { ... }
...

namespace Update
{
    class Update : ConsoleBase
    {
        private static ConsoleBase _consoleBase;
        public static void Main(string[] args) { ... }
...

namespace Query
{
    class Query : ConsoleBase
    {
        private static ConsoleBase _consoleBase;
        public static void Main(string[] args) { ... }
...

It seems like a design problem for me to both inherit from ConsoleBase as well as have an instance of it as a static variable within each derived class. The reason I'm doing this is so that:

  1. I can have protected static methods defined in ConsoleBase that are accessible to other static methods in the derived classes.
  2. I can pass along command-line arguments to the constructor for ConsoleBase, do common stuff, and then access the arguments again in the derived classes via public properties and methods on the instance of ConsoleBase.

So in the derived classes, I have a mixture of calls to methods/properties on the instance of ConsoleBase, e.g.

_consoleBase.UseDebugMode()

As well as calling inherited static methods and accessing inherited constants that are defined in ConsoleBase, e.g.

printWarning(CONST_MSG_IN_BASE_CLASS);

Can I clean this up somehow? Is it bad to both inherit from a class as well as keep an instance of that base class around for working with?

like image 427
Sarah Vessels Avatar asked Dec 29 '25 15:12

Sarah Vessels


1 Answers

Don't mix static and instance methods like this.

Consider, separating the responsibility that the static methods provide into a different class that you can inherit from. Make the non-static functionality a separate class that you aggregate and instantiate within Update and Query.

Besides, if Update and Query are derivatives of ConsoleBase - why do you need the aggregate instances?

like image 81
LBushkin Avatar answered Jan 01 '26 04:01

LBushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!