CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: What does an interface not allowed to have any implementation?

  1. #1
    Join Date
    May 2017
    Posts
    12

    What does an interface not allowed to have any implementation?

    Sometimes it makes sense for interface type class to be super class instead for example the Subject class in observer pattern where it has register, unregister and notify methods. Yet in C#, this would be an interface and this methods has to be implemented in each derived class who wants to send notifications.

    What is the rational about it? It these functions were defined in parent class, it would fascinate code reuse, testability and modularity.

    One can of course have such a class but then multiple inheritance is not allowed as well and it uses the life-line of single inheritance.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,399

    Re: What does an interface not allowed to have any implementation?

    There is no reason you can't use an interface and a base class. While you can only derive from a single base class at a time, you can 'chain' base classes together. Another approach is to use dependency injection and inject the desired functionality into your class. This is probably the more modern approach, and DI is built into .NET Core. If you are new to C#, I suggest you skip learning the older .NET Framework approach and start by learning .NET Core.

  3. #3
    Join Date
    Feb 2017
    Posts
    579

    Re: What does an interface not allowed to have any implementation?

    Quote Originally Posted by caezar View Post
    What is the rational about it? It these functions were defined in parent class, it would fascinate code reuse, testability and modularity.
    There are two kinds of inheritance, inheritance of implementation and inheritance of interface. Inheritance of implementation can lead to the so called fragile base class problem,

    https://en.wikipedia.org/wiki/Fragile_base_class,

    Therefore in object oriented design (OOD) inheritance of interface is preferred. Code reuse is instead achieved by composition which means that a subclass that wants to implement interface methods do so by holding one or more objects (it gets from somewhere) which contain suitable implementation code. It avoids the fragile base class problem but it also allows you to swap implementations at runtime if you would want to. The latter is even an established design pattern called State.
    Last edited by wolle; November 18th, 2020 at 04:48 AM.

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,399

    Re: What does an interface not allowed to have any implementation?

    Out of curiosity I have to wonder how all those C++ devs managed to survive using multiple class inheritance. It seemed to be around for about 20 years before multiple inheritance was deemed evil.

  5. #5
    Join Date
    May 2017
    Posts
    12

    Re: What does an interface not allowed to have any implementation?

    Quote Originally Posted by Arjay View Post
    There is no reason you can't use an interface and a base class. While you can only derive from a single base class at a time, you can 'chain' base classes together. Another approach is to use dependency injection and inject the desired functionality into your class. This is probably the more modern approach, and DI is built into .NET Core. If you are new to C#, I suggest you skip learning the older .NET Framework approach and start by learning .NET Core.
    I am new to C# and don't really understand what you mean by learning the .Net Core and not the .NET framework. Are they really different in terms of routine things? Also I learned that with new .NET 5.0, they are unified.

    And Dependency injection is simply implementing to interface right? If a class Car implments IFly interface then it would mean Car implements the IFly interface?

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,399

    Re: What does an interface not allowed to have any implementation?

    Quote Originally Posted by caezar View Post
    I am new to C# and don't really understand what you mean by learning the .Net Core and not the .NET framework. Are they really different in terms of routine things? Also I learned that with new .NET 5.0, they are unified.

    And Dependency injection is simply implementing to interface right? If a class Car implments IFly interface then it would mean Car implements the IFly interface?
    I'd recommend downloading and installing Visual Studio 2019 community edition. Choose the options to install C# .NET Core and web development.

    Open Visual Studio and choose file/new project. Choose the ASP .NET Core Web Application template. When prompted choose, the REST web service option.

    This will create a new .net core web service solution and project.

    It's a great way to see the built-in Dependency Injection in action.

    Once you create the project, expand the Controllers section and open the WeatherForecastController.cs file.

    Take a look at the constructor:
    Code:
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    When you make a web service request, a new instance of the controller class is dynamically created for you, and the ILogger<WeatherForecastController> logger parameter is injected into your controller class instance.

    Even though this is dependency injection, you may wonder where the ILogger<WeatherForecastController> instance came from.

    Unfortunately that is a bit hidden and its instance was created for you by the .NET Core framework.

    No matter, let's create a new class and inject it into the controller class.

    First we create a 'service' class, and add it to the project:
    Code:
        public interface ICodeguruService
        {
            string Moderator { get; }
        }
    
        public class CodeguruService : ICodeguruService
        {
            public string Moderator { get; } = "Arjay";
        }
    Next we register the class with the dependency injection framework (in startup.cs, find the ConfigureServices method and add the services.AddScoped line):
    Code:
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
                services.AddScoped<ICodeguruService, CodeguruService>(); // add this line
            }
    Next we modify our controller to inject this class...
    So open up the WeatherForecastController class, and replace the following code
    Code:
            private readonly ILogger<WeatherForecastController> _logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    with
    Code:
            private readonly ILogger<WeatherForecastController> _logger;
            private readonly ICodeguruService _codeguruService;
    
            public WeatherForecastController(
                    ILogger<WeatherForecastController> logger,
                    ICodeguruService codeguruService
                )
            {
                _logger = logger;
                _codeguruService = codeguruService;
            }
    Next, modify the Get function to display the Codeguru.Moderator value;

    Just comment out the original and add the new code:
    Code:
            [HttpGet]
            public string Get()
            {
                return _codeguruService.Moderator;
            }
    
    
            //[HttpGet]
            //public IEnumerable<WeatherForecast> Get()
            //{
            //    var rng = new Random();
            //    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            //    {
            //        Date = DateTime.Now.AddDays(index),
            //        TemperatureC = rng.Next(-20, 55),
            //        Summary = Summaries[rng.Next(Summaries.Length)]
            //    })
            //    .ToArray();
            //}
    Now run the web application. A browser window should open and Arjay should be displayed. This value was set when we created the CodeguruService class.
    When we registered this class with .AddScoped, we told the DI framework to create a new instance of the class on every request (e.g. whenever a WeatherForecastController instance was created).

    Admittedly the CodeguruService class doesn't do anything interesting but it does show that an instance of the class was created and injected into the WeatherForecastController class constructor.

    See the attached file for the complete solution.
    Attached Files Attached Files

  7. #7
    Join Date
    May 2017
    Posts
    12

    Re: What does an interface not allowed to have any implementation?

    Quote Originally Posted by Arjay View Post
    I'd recommend downloading and installing Visual Studio 2019 community edition. Choose the options to install C# .NET Core and web development.
    Thanks a lot. I already had 2019 installed and I thought the core was just meant to be for linux, other OSs, I was not sure if the core projects should be used for Windows platforms and why. So they both have different architectures, I didn't know.

    And thanks for posting the project and explaining that. I will dig more into that, you gave me a good start!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)