Internal class with private fields exposed outside using interface

Let’s consider the following situation – there is an internal class Load in our library or plugin. We want to expose our private fields _Q1 and _Q2 as readonly fields using ILoad interface, but we still want to be able to modify the internal content of the fields from the class level. Please note that declaring our private fields using IForce interface makes our fields readonly also from the class level.

As you can see below we can cast our objects to an interfaces using public properties which exposes our objects as readonly fields outside the class.

C# code

    internal class Load : ILoad
    {
        private Force _Q1;
        private Force _Q2;

        public IForce GetQ1
        {
            get
            {
                return (IForce)_Q1;
            }
        }

        public IForce GetQ2
        {
            get
            {
                return (IForce)_Q2;
            }
        }

        public Load()
        {
            _Q1 = new Force();
            _Q2 = new Force();
        }

        public IAddQ1Condition WithQ1
        {
            get
            {
                return new AddQ1(_Q1);
            }
        }

        internal class AddQ1 : IAddQ1Condition
        {
            private Force _q1;

            public AddQ1(Force q1)
            {
                _q1 = q1;
            }

            public IAddQ1Condition Value(double value)
            {
                _q1.Value = value;
                return this;
            }
        }
    }

    public interface ILoad
    {
        IForce GetQ1
        {
            get;
        }

        IForce GetQ2
        {
            get;
        }

        IAddQ1Condition WithQ1 { get; }

        IAddQ2Condition WithQ2 { get; }
    }

    public interface IForce
    {
        double GetValue
        {
            get;
        }

        double GetPosition
        {
            get;
        }

        double GetApplicationLevel
        {
            get;
        }
    }

C# result

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s