none
Retrieve current value in the set accessor RRS feed

  • Question

  • Hello everyone,

    is there a way to have the current value of a property, without know the name of the property, in his set accessor?

    I've got 10+ properties, in the set accessor I've to do something using the current value, so atm I wrote something like:

    public string V1
    set
    {
        myFunc(this.V1)
    }
    
    public string V2
    set
    {
        myFunc(this.V2)
    }
    
    public string V3
    set
    {
        myFunc(this.V3)
    }

    Is there something like:

    public string V1
    set
    {
        myFunc(ThisVariableValue)
    }
    
    public string V2
    set
    {
        myFunc(ThisVariableValue)
    }
    
    public string V3
    set
    {
        myFunc(ThisVariableValue)
    }
    

    ?

    Friday, September 13, 2019 4:51 PM

All replies

  • I don't understand what you're asking. Your code isn't valid C# so it is hard to even see what you are trying to accomplish.

    A property is just a glorified get/set method (either is optional). It is unclear what you mean by knowing the property value without knowing the property. I cannot even begin to imagine the problem you're trying to solve.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, September 13, 2019 5:08 PM
    Moderator
  • Hi Andrea,

    sure just use the keyword 'value', here is an example that use a backing field reference and the current value: 

    public void SetProperty<TProperty>(ref TProperty backingField, TProperty value) {
        backingField = value;
    }
    
    public void MyFunc<TValue>(TValue value) {
        Debug.WriteLine(value);
    }
    
    // if you need to get the property name on your method use this code 
    
    public void MyFunc<TValue>(TValue value, [CallerMemberName] string propertyName = "") {
        Debug.WriteLine(value);
    }
    
    private string _v1;
    public string V1
    set
    {    // at low level the setter is method that take a value as argument, the value keyword is used to access this argument 
        MyFunc(value);
        SetProperty(ref _v1, value);
    }
    
    private string _v2;
    public string V2
    set
    {
        MyFunc(value);
        SetProperty(ref _v2, value);
    }
    
    private string _v3;
    public string V3
    set
    {
        MyFunc(value);
        SetProperty(ref _v3, value);
    }

    Best Regards,

    Mouad.


    Friday, September 13, 2019 5:11 PM