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? Tricky, right?
Let me explain. 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? Simple, here is the modified BusinessEntity class.
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();
Check it out!
Thanks,
Joydip