Home > Enterprise >  Derived class from static class?
Derived class from static class?

Time:01-18

I can't quite grasp the inheritance thing. I need a very simple to imagine thing - modify System.Console class method WriteLine to write not only in console, but also in text log file.

I simply need to run this function with preset arguments prior to any call to WriteLine and then do generic WriteLine:

class Logger
{
    static public void WriteLog(string logMessage, string fileName ,bool addTimeStamp = true)
    {
        //Getting temp folder
        string destPath = Path.GetTempPath();

        //Creating folder
        if (!Directory.Exists(destPath))
            Directory.CreateDirectory(destPath);

        //Naming log file
        var filePath = String.Format("{0}\\{1}.log",
            destPath,
            fileName
            );

        //Writing to timestamp
        if (addTimeStamp)
        {
            logMessage = String.Format("[{0}] - {1}{2}",
                DateTime.Now.ToString("HH:mm:ss", CultureInfo.CurrentCulture),
                logMessage,
                Environment.NewLine);
        }
        else
        {
            logMessage = String.Format("{0}{1}",
                logMessage,
                Environment.NewLine);
        }
        //Writing to log
        File.AppendAllText(filePath, logMessage);
    }
}

But I cannot even create a class since "Static class ConsoleX cannot derive from type Console. Static classes must derive from object". Is there at all simple way to wrap around WriteLine method? I would do a separate (not inherited) class for it but then I need to create like 18 overloads for this method just to pass through arguments to 18 overloads of generic WriteLine, so it feels like waste of effort for seemingly simple thing.

CodePudding user response:

It is not possible to create a derived class from a static class in C#. A static class is a class that cannot be instantiated and therefore cannot be inherited from. Instead, you can use a regular class or an abstract class as a base for a derived class.

CodePudding user response:

yes you are right, you cannot inherit from the static class, instead you can create extension method.

public static class ConsoleExtensions
{
    public static void WriteLineWithLog(this Console console, string logMessage, string fileName, bool addTimeStamp = true)
    {
      //your code
       
    }
}

then you can simply call like Console.WriteLineWithLog("Hello, World!", "MyLogFile.log");

with extension methods you dont need to modify the existing class to add new methods into it

  •  Tags:  
  • c#
  • Related