Search code examples
c#interface

How can I make a method private in an interface?


I have this interface:

public interface IValidationCRUD
{
    public ICRUDValidation IsValid(object obj);
    private void AddError(ICRUDError error);
}

But when I use it (Implement Interface, automatic generation of code), I get this:

public class LanguageVAL : IValidationCRUD
{   
    public ICRUDValidation IsValid(object obj)
    {
        throw new System.NotImplementedException();
    }

    public void AddError(ICRUDError error)
    {
        throw new System.NotImplementedException();
    }   
}

The method AddError is public and not private as I wanted.

How can I change this?


Solution

  • An interface can only have public methods. You might consider using an abstract base class with a protected abstract method AddError for this. The base class can then implement the IValidationCRUD interface, but only after you have removed the private method.

    like this:

    public interface IValidationCRUD
    {
        ICRUDValidation IsValid(object obj);
    }
    
    public abstract class ValidationCRUDBase: IValidationCRUD {
        public abstract ICRUDValidation IsValid(object obj);
        protected abstract void AddError(ICRUDError error);
    }