Question

i have a few classes with multiple strings, i want to raise different events depending on what string has changed. here's an example

class textClass: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string text1;
    public string Text1
    {
        get { return text1; }
        set
        {
            text1 = value;
            NotifyPropertyChanged("Text1");
        }
    }

    private string text2;
    public string Text2
    {
        get { return text2; }
        set
        {
            text2 = value;
            NotifyPropertyChanged("Text2");
        }
    }

    //used as notifier when a string changes within this class
    private void NotifyPropertyChanged(string info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (PropertyChanged != null)
            handler(this, new PropertyChangedEventArgs(info));
    }
}

so in my main class, if i use

txtClass.PropertyChanged += new PropertyChangedEventHandler(txtClass_PropertyChanged);

how do i NOT use an "if" statement to evaluate the string like this:

static void txtClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Text1")
            Console.Write("yadda yadda1");
        if (e.PropertyName == "Text2")
            Console.Write("yadda yadda2");
    }

if i have 70 or 80 strings, that method is never going to stop.

is there another way of doing this?

Was it helpful?

Solution

Use a dictionary of the different expected strings and do a lookup then spit out the resulting value

var dict = new StringDictionary();
dict.Add("Text1", "yadayad");
// add the rest


var val = dict[property_name];
if (val != null)
{
   Console.WriteLine(val);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top