Like the other answer it is legal from c#8.0.
But is there any benefit of having abstract methods in interface??
With recent improvements in the language, abstract
function in interface can be considered as something which will not have default implementation.
Now the C# interfaces can have default implementation for interface functions. Look at the below example. It is totally fine and the output is "Default implemented example function".
//AN INTERFACE WITH DEFUALT METHOD
interface I
{
string Example()
{
return "Default implemented example function";
}
}
//CLASS IMPLEMENTING THE INTERFACE
class C : I
{
}
//AN EXAMPLE CLASS ACCESSING THE DEFAULT IMPLEMENTED example FUNCTION.
public class Test
{
public static void Main(string[] args)
{
I i = new C();
Console.WriteLine (i.Example());
}
}
In the above example lets suppose try adding abstract
for the "Example()" function in Interface.
The code will not compile saying "'I.Example()' cannot declare a body because it is marked abstract"
So when we use abstract
the obvious way is to define the function in the class (implements interface) for any usage(shown below).
//AN INTERFACE WITH ABSTRACT METHOD
interface I
{
abstract string Example();
}
//CLASS IMPLEMENTING THE INTERFACE AND GIVE A BODY FOR EXAMPLE FUNCTION
class C : I
{
public string Example()
{
return "Implemented example function";
}
}
//A CLASS ACCESSING THE CLASS METHOD EXAMPLE.
public class Test
{
public static void Main(string[] args)
{
I i = new C();
Console.WriteLine (i.Example());
}
}
In summary declaring the function in interface as abstract
, there can not be a default body for the function in interface, instead the class implements the interface must have a body for it.