The ref keyword when passing an uninitialized parameter to a method

An abstract base class BindableBasein a project WinRTis defined as follows:

[Windows.Foundation.Metadata.WebHostHidden]
public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (object.Equals(storage, value)) return false;

        storage = value;
        this.OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

It's good.

Now I see a lot of articles trying to implement this class by doing such things as follows:

private  int _timeEstimate;
        public int TimeEstimate
        {
            get { return this._timeEstimate; }
            set { this.SetProperty(ref this._timeEstimate, value); }
        }

_timeEstimate is not initialized, how can it be passed using ref?! is there something i'm missing? it really upsets me that I am missing, I even find the same letter in Microsoft exam preparation books!

+4
source share
1 answer

_timeEstimate - . a class ( , ). a struct , (side note: technicalically struct , # IL , new SomeStruct() : p)

: .

.

+6

Source: https://habr.com/ru/post/1527312/


All Articles