6

I defined a method using ref object as parameter. When I try to call it with a ref List, it told me can't convert from ref List to ref object. I have done lots of search to find a answer. However most answers are "you don't need ref here" or there are work arounds.

It seems there is no way to convert from 'ref [Inherited]' to 'ref [Base]', even using ref (Base)[Inherited]. Don't know if I'm right.

What I want is writing only 1 line in the set { } block to change the value and send notification. Any suggestions?

class CommonFunctions
{
    public static void SetPropertyWithNotification(ref object OriginalValue, object NewValue, ...)
    {
        if(OriginalValue!= NewValue)
        {
            OriginalValue = NewValue;
            //Do stuff to notify property changed                
        }
    }
}
public class MyClass : INotifyPropertyChanged
{
    private List<string> _strList = new List<string>();
    public List<string> StrList
    {
        get { return _strList; }
        set { CommonFunctions.SetPropertyWithNotification(ref _strList, value, ...);};
    }
}
Wenpeng
  • 63
  • 1
  • 4

1 Answers1

4

Use generics and Equals method

class CommonFunctions
{
    public static void SetPropertyWithNotification<T>(ref T OriginalValue, T NewValue)
    {
        if (!OriginalValue.Equals(NewValue))
        {
            OriginalValue = NewValue;
            //Do stuff to notify property changed                
        }
    }
}
public class MyClass
{
    private List<string> _strList = new List<string>();
    public List<string> StrList
    {
        get { return _strList; }
        set { CommonFunctions.SetPropertyWithNotification(ref _strList, value); }
    }
}
Backs
  • 24,430
  • 5
  • 58
  • 85
  • Another question what to make sure. Is it always illegal to convert from ref[Inherited] to ref[Base] ? – Wenpeng Aug 08 '15 at 04:09
  • @Wenpeng no, it's because of `ref` keyword. Because you can assign new value to ref parameter and it must match initial parameter type – Backs Aug 08 '15 at 04:11