How can I force an object to be called only via its interface? That can only accomplish via Access Modifier but in C# can’t do.
I have:
public interface IProfile { string GetName(); }
public class Profile : IProfile {
public string GetName() { return "Linh"; }
}
I have a code section like that above. I put it in a class library after that I generate an assembly.
In a web project some programmers will add reference to that assembly. If they want to call Profile class then they must use IProfile interface as declaration below:
IProfile ip = new Profile();
ip.GetName();
But some careless programmers won’t do so. They will use below way:
Profile pr = new Profile();
pr.GetName();
This is really simple. Use an explicit interface implementation:
GetNamecan now only be called through an interface reference.