Introduction
Paragraph Heading 1 If we implement interface methods implicitly, we are able to use the method with objects of the interface type or of the implementing class type. If we are implementing explicitly, the method will only work on the interface. The greatest benefit of only allowing instances of the interface to use the method is that it encourages you to write more dynamic and maintainable code since you'll be using the interface everywhere you'll be able to switch your implementing classes quickly and easily. This is one of many great ways to write better code. You can restrict creating instances of classes using C# in more ways than one. You can make the class abstract, static or even use a private constructor. But, what if you want to allow a method of a class to be invoked only using an interface reference, i.e., the interface that the class implements?
Paragraph Heading N
Here is an interface called IBusinessEntity that the class BusinessEntity implements. public interface IBusinessEntity { void Serialize(); } It contains only one method called Serialize. Now, here is the BusinessEntity class. public class BusinessEntity : IBusinessEntity { public void Serialize() { //Some code } } Now, you can instantiate the BusinessEntity class and invoke the Serialize() method using any of following ways. IBusinessEntity bE = new BusinessEntity(); bE.Serialize(); or BusinessEntity bE = new BusinessEntity(); bE.Serialize(); What if you want to restrict to the former only? Here is the modified BusinessEntity class that illustrates how we can implement the Serialize() method explicitly. public class BusinessEntity : IBusinessEntity { void IBusinessEntity.Serialize() { //Some code } } Now, you can invoke the Serialize() method only using the statements shown below. IBusinessEntity bE = new BusinessEntity(); bE.Serialize();
Summary
|
No responses found. Be the first to respond and make money from revenue sharing program.
|