Can we define body of Interfaces methods? When to define methods in Interfaces?

Yes, you can define the body of an interface method in C# 8.0. This is known as a default interface method. Default interface methods allow you to provide a default implementation for a method in an interface, so that classes that implement the interface do not have to implement the method themselves.

There are a few reasons why you might want to define a default interface method:

  • To provide a common implementation for a method across multiple classes. This can save you time and effort, as you do not have to implement the method in each class that implements the interface.
  • To provide a base implementation for a method that can be overridden by classes that implement the interface. This allows classes to customize the behavior of the method without having to rewrite the entire method.
  • To enforce a minimum level of functionality for classes that implement the interface. By providing a default implementation for a method, you can ensure that all classes that implement the interface provide at least a basic level of functionality.

When to define methods in Interfaces?

You should only define methods in an interface when it is necessary to do one of the following:

  • Enforce abstraction. Interfaces are used to define the behavior of a class, but not how that behavior is implemented. By defining methods in an interface, you can enforce abstraction and prevent classes from implementing the methods in any way that you do not approve of.
  • Provide a common implementation for a method across multiple classes. This can save you time and effort, as you do not have to implement the method in each class that implements the interface.
  • Provide a base implementation for a method that can be overridden by classes that implement the interface. This allows classes to customize the behavior of the method without having to rewrite the entire method.
  • Enforce a minimum level of functionality for classes that implement the interface. By providing a default implementation for a method, you can ensure that all classes that implement the interface provide at least a basic level of functionality.

Here is an example of a default interface method in C# 8.0:

public interface IAnimal
{
    void Speak();
    default void SpeakLoudly()
    {
        Console.WriteLine("I am speaking loudly!");
    }
}

The Speak() method is a default interface method. It has a default implementation that prints a message to the console. Classes that implement the IAnimal interface can choose to override the Speak() method, or they can use the default implementation.


 

Post a Comment

Previous Post Next Post