0

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:

  • Add a setter to IFreezableEntity (which I don't want)
  • Convert it to a regular public property with a private set (I might as well just leave the private bool isFrozen;)

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

Adam G
  • 1,283
  • 1
  • 6
  • 15
  • @Keith-Nicholas, my question is different. Which answer to that question do you believe pertains to this question? – Adam G Aug 10 '18 at 04:50
  • it's the same problem, you want to use a auto property, you can't so you have to keep your isFrozen.... just like the other question. – Keith Nicholas Aug 10 '18 at 05:05

0 Answers0