System.ComponentModel.BindingList: Add(object) vs. AddNew()
Asked Answered
T

2

11

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?

Turnstone answered 17/4, 2012 at 19:45 Comment(2)
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.Pinchhit
@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!Worthy
H
12

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().

Hyperthermia answered 17/4, 2012 at 19:49 Comment(0)
N
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.

Nottage answered 13/12, 2021 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.