Home > Back-end >  How do I implement an interface in new VS2022 console app
How do I implement an interface in new VS2022 console app

Time:03-08

I'm working along the following article about Window Services for .Net Core here

How do I implement the interface "ServiceBase" when I can't see the class keyword?

class LoggingService : ServiceBase
{
    private const string _logFileLocation = @"C:\temp\servicelog.txt";
    private void Log(string logMessage)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_logFileLocation));
        File.AppendAllText(_logFileLocation, DateTime.UtcNow.ToString()   " : "   logMessage   Environment.NewLine);
    }
    protected override void OnStart(string[] args)
    {
        Log("Starting");
        base.OnStart(args);
    }
    protected override void OnStop()
    {
        Log("Stopping");
        base.OnStop();
    }
    protected override void OnPause()
    {
        Log("Pausing");
        base.OnPause();
    }
}

The new Prograam.cs in VS2022

// See https://aka.ms/new-console-template for more information

using ClassLibrary1;

var result = Class1.AddNumbers(1, 2);
Console.WriteLine($"1 2={result}");

CodePudding user response:

you have to write it out in full, the syntax you are using is a shorthand that supports limited things

public class MyService :ServiceBase{
  .. implement service base here
}
public static class Program
{
    public static void Main()
    {
        // use it here       
    }
}

its unfortunate that vs2022 produces this by default since its so limited

CodePudding user response:

I misunderstood the article the 2nd time around. The code shown above was just a regular class that Program.cs called out to. Sorry about that.

CodePudding user response:

This code

using ClassLibrary1;

var result = Class1.AddNumbers(1, 2);
Console.WriteLine($"1 2={result}");

is just a shorthand equivalent of the following

using ClassLibrary1;

public static class Program
{
    public static void Main()
    {
        var result = Class1.AddNumbers(1, 2);
        Console.WriteLine($"1 2={result}");
    }
}

So, you can use the "full" version then add inheritance and so on.

You can found additional information about this shorthand version by the link https://aka.ms/new-console-template

  • Related