Rohan Sampat
Rohan Sampat

Reputation: 970

Application breaks while get set of property in xamarin

I am new to Xamarin. I have created a test app where a data in text field will update a label, when I set label value static via model, it works well but when i try to update label value dynamically the application breaks.

class Properties : INotifyPropertyChanged
{
    public string Res { get; set; } // This works fine.
    public string Dept 
    {
        get { return Dept; } /// This cause the application to break whithout even notifying any error
        set
        { 
            if (Dept != value)
            {
                Dept = value;
                OnPropertyChanged(nameof(Dept ));
            }
        } /// This cause the application to break whithout even notifying any error
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var propertyChangedCallback = PropertyChanged;
        propertyChangedCallback?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

Help is really appreciated.

Upvotes: 0

Views: 94

Answers (1)

Cheesebaron
Cheesebaron

Reputation: 24470

The issue is that you have a infinite loop.

This is because you are accessing the property Dept in its own getter and setter. This will infinitely try to call the getter or setter and eventually crash.

To solve this you have to add a backing field like:

private string _dept;
public string Dept
{
    get => _dept;
    set
    {
        if (_dept != value)
        {
            _dept = value;
            OnPropertyChanged(nameof(Dept));
        }
    }
}

Upvotes: 3

Related Questions