Adam G
Adam G

Reputation: 1333

Is it possible to use an auto property with an explicit interface implementation?

I have an interface that looks like this

public interface IFreezableEntity
{
    bool IsFrozen { get; }
    void Freeze();
}

And a class that looks something like this:

public class Foo : IFreezableEntity
{
    private bool isFrozen;

    bool IFreezableEntity.IsFrozen => this.isFrozen;

    void IFreezableEntity.Freeze()
    {
        // Do useful work
        this.isFrozen = true;
    }

    public void CanNotDoWhileFrozen()
    {
        if (this.isFrozen)
        {
            throw new MethodAccessException($"{nameof(this.CanNotDoWhileFrozen)} should not be called on a Frozen instance");
        }
        // Do some work
    }

    public void CanOnlyDoWhileFrozen()
    {
        if (!this.isFrozen)
        {
            throw new MethodAccessException($"{nameof(this.CanOnlyDoWhileFrozen)} should not be called unless instance is Frozen");
        }
        // Do some work
    }
}

I want to use explicit implementation of the interface because these are not methods that the consumers of my class should typically call. This works, but ideally, I would like to remove the backing isFrozen field.

I can change the read references of if (this.isFrozen) to if (((IFreezableEntity)this).IsFrozen) easy enough.

My problem is that if I define it as an auto property

    bool IFreezableEntity.IsFrozen
    {
        get;
    }

then I don't see how I can set it's value, unless I either:

My goal is to encapsulate the properties that are there for its IFreezableEntity logic from the other logic that will be in Foo.

Upvotes: 0

Views: 30

Answers (0)

Related Questions