Blazing onto the scene in the new C# 8 implementation is the introduction of default interface methods. This is probably one of the more controversial language additions that developers will really like or hate. In this post, I will describe this new feature and some of the reservations that developers will have in embracing this. Also note that this feature has been present in Java for quite some time.
When you think of an interface, you think of it as a contract. Any class that implements that interface MUST meet the contract obligations (i.e. include any member properties and functions that are defined in said interface). Interfaces are also used in dependency injection to instantiate (hydrate) objects for a defined period of time.
Now that you know what an interface is and what it's used for, why do we need default interface members?
The answer is that we don't. Default interface methods don't improve performance. They don't increase maintainability. They questionably violate the entire purpose of the existence of an interface to begin with. What they do help with is code conservation. I no longer have to write as much code to implement an interface member if I know that it will be the same code in every single class that uses it. Also, I can also add a new default method to an existing interface without breaking the implementing classes.
So, is it good? Is it bad? Depends on your use. Admittedly, this feature does skirt the fine line of violating what an interface is and does, but also provides some very useful and clever features that we can take advantage of.
Lets take a look at this feature:
public interface IDefaultInterfaceMethod
{
public void DefaultMethod()
{
Console.WriteLine("I am a default method in the interface!");
}
}
class AnyClass : IDefaultInterfaceMethod
{
}
class Program
{
static void Main()
{
IDefaultInterfaceMethod anyClass = new AnyClass();
anyClass.DefaultMethod();
}
}
This will output the following to the console:
I am a default method in the interface!
By default, the default interface methods are virtual unless the sealed or private modifier is used. Similarly, abstract is the default on interface members without bodies.
Subscribe to:
Post Comments (Atom)
New Features in .Net 10
🚀 Runtime Enhancements Stack Allocation for Small Arrays The Just-In-Time (JIT) compiler now optimizes memory usage by stack-allocating s...
-
Microservices architectures are designed to be scalable, resilient, and independent, but they introduce significant challenges in ensuring...
-
What exactly is .NET Aspire? .NET Aspire is Microsoft’s opinionated application stack for building observable, production-ready, distribute...
-
DBUp vs FluentMigrator for .NET + PostgreSQL Why We Landed on FluentMigrator Database migrations are one of those invisible chores that ca...
No comments:
Post a Comment