This past month of May/2019 was quite hectic within the .NET community, with the announcement of new updates for Visual Studio 2019 and .NET Core 3.0. With these new versions, one of the most anticipated features for C# 8.0 has also been made available for testing: Default Interface Members.
Now allowing methods implementations and properties to be declared in an interface, this new functionality helps to avoid code breaking when it is necessary to include new members in these structures.
In the following listing, we have an example involving the IPrestadorServico interface, in addition to the classes PessoaFisica and PessoaJuridica as two possible implementations of it:
We can test the use of Default Interface Members with the structures presented here as an example through the following changes:
-> Declaring the PossuiCNPJ property in IPrestadorServico, and assigning true, as the default value. This same property can also be redefined in PessoaFisica to return false, while no change will happen in PessoaJuridica;
-> With the ObterDescricaoGeral method, without making changes to PessoaFisica and PessoaJuridica.
It is important to note that members with default implementation that have not been redefined in classes that derive from an interface will not be available for direct access. What does this mean in practice for this last example?
With a reference based on PessoaFisica or PessoaJuridica, the ObterDescricaoGeral method will not be available. Variables declared as being of type IPrestadorServico will have access to such method.
The PossuiCNPJ property will only be available for variables declared as belonging to the PessoaFisica class or based on the IPrestadorServico interface. This property will not be available for direct access via a reference of type PessoaJuridica.
These points are illustrated in the following image:
The next listing brings an example of using the types PessoaFisica and PessoaJuridica in a Console Application, with the ImprimirDadosPrestador method receiving references based on these classes as a parameter:
The following is the result of running this project:
If you want to know more about other news that makes up C# 8.0, visit the following post, where I group all the content I’ve been producing about this version:
C# 8.0 – Reference Guide: articles, videos, and usage examples
And also the recording of a recent presentation on .NET channel, in which MVP André Secco and I presented in detail the innovations of C# 8.0:
References
Leave a comment