0

Just as title says, how to fire property when I do propertyList.Add(something)

So code is:

private List<string> _SomeStrings;

public List<string> SomeStrings
{
    get
    {
        return _SomeStrings;
    }
    set
    {
        _SomeStrings = value;
    }
    odAdd //this is what I need but do not know how to do it
}
Pacijent
  • 139
  • 1
  • 12

3 Answers3

1

You can either use a built in type such as ObservableCollection; examples here and here. MSDN page.

You could also create a new class that derives from List, and overloads the functions you wish to hook.

class ListWithAdd<T> : List<T>
{
    public new void Add(T item)
    {
        base.Add(item);
        DoStuff();
    }
}
Blam
  • 2,888
  • 3
  • 25
  • 39
0

Create a custom generic list, create a event which will be fired when an item is added in the list.

like this:

namespace ConsoleApplication2
{
    public delegate void OnAddEventHandler(object item);

    public class AddEventArgs : EventArgs
    {
        public object item { get; set; }
    }

    public class MyList<T> : List<T>
    {
        public event OnAddEventHandler OnAdd;
        public new void Add(T item)
        {
            base.Add(item);
            if (OnAdd != null)
            {
                OnAdd(item);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyList<string> lst = new MyList<string>();
            lst.OnAdd += (item) => {
                Console.WriteLine("new item added: " + item);
            };
            lst.Add("test");

            Console.ReadLine();
        }
    }
}

here's fiddle for you: https://dotnetfiddle.net/tc5Mq1

Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98
-1

Look into observablecollection https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.7.2

Aldert
  • 4,209
  • 1
  • 9
  • 23
  • Answering questions by just referencing to other site link is not good choice. the links can be die later and the answer is unusable. add description and code directly to your answer. – Mojtaba Tajik Sep 15 '18 at 09:00
  • I would agree with you when code was provided, in this case it is an open question so I provide a possible solution. The link is to a microsoft doc so unlikely it dies. – Aldert Sep 15 '18 at 09:23
  • The content of document always available in sites like Microsoft but the URL if theme changes in time by changing the routes. you can find many Microsoft documentation links that currently is dead in Google searches. – Mojtaba Tajik Sep 15 '18 at 09:40