How I can Prevent interface method that I implemented in a class from being instantiated.
public interface Interface1
{
void Show();
}
public class ABC : Interface1
{
public void Show()
{
// any thing
console.WriteLine(:Hello");
}
}
class Program
{
static void Main(string[] args)
{
ABC a = new ABC();
}
}
Here in program class I dont want to create the access this method.
You can use explicit interface implementation, if you really only want the method to be available via an expression of the interface type:
void Interface1.Show()
{
throw new NotImplementedException();
}
You can't remove the possibility of calling it completely though - that would clearly break the fact that ABC
implements the interface at all. Indeed, if it's not going to really implement the whole interface, you should consider whether or not it should declare that it implements the interface.
With explicit interface implementation as above: we'd have:
ABC abc = new ABC();
abc.Show(); // Error
Interface1 iface = abc;
iface.Show(); // Fine at compile time; will throw your NotImplementedException
See more on this question at Stackoverflow