Default implementation of interface members

We all know that, in C#, interfaces don't have any method implementations, they only contain the method signature. In C# 8, however, interfaces are allowed to have implemented methods. These methods can be overridden by classes if they need to be. Interface methods will also have access to modifiers, such as public, virtual, protected, or internal. By default, the access level is set to virtual unless it is fixed as sealed or private.

There is another important thing to note. No attributes or fields are yet allowed in an interface. This means that interface methods can't use any instance fields in the methods. Interface methods can take parameters as input and use those, but not instance variables. Let's take a look at an example of an interface method:

using System;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
IPerson person = new Person();
person.PrintName("John", "Nash");
Console.ReadKey();
}
}
public class Person : IPerson
{
}
public interface IPerson
{
public void PrintName(string FirstName, string LastName)
{
Console.WriteLine($"{FirstName} {LastName}");
}
}
}
At this time of writing the book, this feature has not been yet available in the C# 8 preview version. This is still marked as proposed feature but hopefully it will be implemented in the final release. So the above given code might not work even if you use Visual Studio 2019 preview version.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.200.164