10

What is the difference between the System.ComponentModel.BindingList methods Add(object) and AddNew()? The MSDN documentation says this:

  • Add: Adds an object to the end of the Collection<T>.

  • AddNew: Adds a new item to the collection.

It seems like both methods add an item to the collection, but Add(object) does it in one shot whereas AddNew() is slightly more complicated. My tests with Add(object) seem to be working, but I want to know if I am using the correct method.

So what is the difference between these methods?

user1214135
  • 625
  • 2
  • 11
  • 22
  • 4
    AddNew adds an 'empty' object. Only the default constructor was run. It raises the AddingNew event to allow other classes to customize the object initialization. Note that EndNew must be called after setting its properties. It isn't clear which one is 'better' in your case. Simple is better. – Hans Passant Apr 17 '12 at 19:59
  • 1
    @HansPassant you are a life-saver! I was experiencing weird behavior because I was not calling `.EndNew` and I was so confused. The metadata on `.AddNew` really should mention this requirement! – Carl G May 19 '12 at 09:06

2 Answers2

11

AddNew() creates the object for you (that's why it doesn't have a parameter).
It's designed to be used by grids, which don't know how to create a new object to pass to Add().

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

AddNew() is very handy (it’s the well-known Factory design pattern) when you implement a class derived of BindingList().

It allows your code to initialize new items with values that depend on the list itself - e.g. a foreign key to the parent object if the binding list contains a list of children.