Dependent properties in C#

Posted on

Problem

BountyHunter has a secure line named JobLine that provides them with Prey to hunt.

The Prey can be changed at any time, either from the JobLine or changing circumstances that make the bounty hunter choose to swap targets.

How can I improve the dependent / calculated property that is being delegated from the BountyHunter to the JobLine ?

using Microsoft.Practices.Prism.ViewModel;

namespace TestBindings
{

    public class Prey
    {
        public Prey()
        {
        }
    }

    //Prey Provider
    public class JobLine : NotificationObject
    {
        public JobLine(Prey prey)
        {
            this.Prey = prey;
        }

        private Prey _prey;

        public Prey Prey
        {
            get { return _prey; }
            set
            {
                if (_prey != value)
                {
                    _prey = value;
                    RaisePropertyChanged(nameof(Prey));
                }
            }
        }
    }


    public class BountyHunter : NotificationObject
    {
        public BountyHunter(JobLine jobLine)
        {
            JobLine = jobLine;
        }

        public Prey Prey
        {
            get { return JobLine.Prey; }
            private set
            {
                if (JobLine.Prey != value)
                {
                    JobLine.Prey = value;
                    RaisePropertyChanged(nameof(Prey));
                }
            }
        }

        private JobLine _jobLine;

        public JobLine JobLine
        {
            get { return _jobLine; }
            private set
            {
                if (_jobLine != value)
                {
                    _jobLine = value;
                    RaisePropertyChanged(nameof(JobLine));
                    RaisePropertyChanged(nameof(Prey));
                }
            }
        }
    }
}

Solution

Is there any reason why you implemented the same logic/property twice? JobLine already has a property called Prey:

public Prey Prey
{
    get { return _prey; }
    set
    {
        if (_prey != value)
        {
            _prey = value;
            RaisePropertyChanged(nameof(Prey));
        }
    }
}

so why does BountyHunter have it too if I can access Pray via JobLine?

public Prey Prey
{
    get { return JobLine.Prey; }
    private set
    {
        if (JobLine.Prey != value)
        {
            JobLine.Prey = value;
            RaisePropertyChanged(nameof(Prey));
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *