Search code examples
c#winforms.net-4.0idictionary

adding a before event to either an IDictionary or class


Is it possible to create an event before an item is added or updated to an IDictionary?

public static IDictionary<string, Aircraft> aircraftList = new Dictionary<string, Aircraft>();

and I use it like this

MainForm.aircraftList[acNumber].FlightStatus = strFlying;

What I want to do is not to update the value if the new value is null, empty string or an int == 0

Aircraft is a class with lots of values which are a mix of strings int's and doubles...

or is there a way of doing this type of action within the class?

currently I'm doing this everywhere I assign a value via an if statement, I assume there is a better way?


Solution

  • You could roll out your own Dictionary class and use custom Add() function (and other functions). Something like this:

    class MyCustomDictionary : Dictionary<string, Aircraft>
    {
      public new Add(string key, Aircraft value)
      {
        if (YOUR_CONDITION)
        {
          base.Add(key, value);
        }
      }
    }
    

    You should note the use of new keyword here. The Add() function cannot be overridden because the base class doesn't define it as overridable. So you must use new in your definition.