0 votes
by (2.5k points)
I was always taught that interfaces do not have methods in C# (They are like a contract), but in recent times I've seen developers write code that has interfaces having methods (And it compiles). So can an interface have a method or not?

1 Answer

0 votes
by (2.5k points)
In C# 8 (circa 2018), "Default Interface Implementations" were added to the C# spec. It essentially allows an interface to provide a "default" method implementation should the class implementing the interface not want to write one themselves.

The actual reasoning behind it was that many .NET types, such as IEnumerable, have many thousands of implementations out there in the wild. Adding any additional method declarations to this would break quite literally thousands of applications world wide. So being able to add a method to IEnumerable, and essentially say "You can implement this or I've done a version for you so you don't have to" means that any code that's implementing IEnumerable won't instantly break.

So the short answer is, yes, since C# 8, interfaces can have method bodies.

For further reading you can check out this post here : https://dotnetcoretutorials.com/2018/03/25/proposed-default-interface-methods-in-c-8/
Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...