Interface Having Method With Body In C# 8.0

The latest version of C# allows you to define the body of the interface method.
For example, consider you have a project of Asset Management which has an interface, IAsset, that has properties AssetName, AssetAge, Id and so on.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  7. namespace Stucts.New_Features.Interface  
  8.    {  
  9.    interfaceIAsset  
  10.    {  
  11.       string AssetName { getset; }  
  12.       string AssetAge { getset; }  
  13.       string Id { getset; }  
  15.    }  
  16. }  
Now, consider you have this interface inherited in multiple classes, like FixedAssets, TemporaryAssets, and so on.
  1. using System;  
  2. using Stucts.New_Features.Interface;  
  4. namespace Stucts.New_Features  
  5.    {  
  6.    class FixedAsset : IAsset  
  7.       {  
  8.          public string AssetName { get; set ; }  
  9.          public string AssetAge { get; set; }  
  10.          public string Id { get; set; }  
  11.       }  
  12. }  
Consider you want to add this new feature to your application which moves the asset to archive after certain years as per customer needs. It may be possible that you need to implement this logic for all kinds of assets or just for a few or some different logic based on other calculations.
In the older version of C#, you need to define a non-body method in the interface and implement that method in all the other classes. In some cases, this might not seem a very big issue but I know when you are working on ultra-large-scale software, then this is a headache no one wants.
In C# 8.0, you can define the default implementation of a method in interface and classes can use that method or if you can give a different definition to the same method in child classes.
  1. public void MoveAssetToArchive(int age)  
  2. {  
  3.    //Your log here  
  4. }  
You can start using this method in all the child classes without implementing it.
  1. FixedAsset _fixAsset = newFixedAsset() {  
  2.    AssetAge="4",  
  3.    AssetName="HTC Explorer Mobile phone",  
  4.    Id = "1001"  
  5.    };  
  6. IAsset _IAsset = _fixAsset;  
  7. _IAsset.MoveAssetToArchive(4);  
Notice the following section of the test.
  1. IAsset _IAsset = _fixAsset;  
  2. _IAsset.MoveAssetToArchive(4);  
Well, that saved a lot of time and efforts :)
Similarly, you can also declare a variable as well as static members in the interface.
I would love it if you guys create a demo project with a scenario where we might need to declare static members and behaviors in an interface. Please do try. I will create a demo with a scenario and write it in the blog soon so that we can discuss it. Comment if you have any question or want to discuss something.
Meanwhile, follow and subscribe to the blog to get notifications of it.

Next Recommended Reading Expression - Bodied Methods in C# 6