I am confused on when to use SPItem vs SPListItem—specifically when grabbing items from a document library. What are the benefits of each and downsides of each.
2 Answers
SPItem is just an abstract class that SPListItem inherits from. From MSDN's documentation:
Abstract base class that constitutes the data transport item upon which forms operate.
You do not want to work with SPItem because it is an abstract class which cannot be instantiated. Abstract classes are very similar to Interfaces in OOP. Give this article a read to get a better understanding of Abstract Classes.
Still, properties can still be accessed from that class.
For example, if you pass an SPListItem
object as a parameter and only use properties defined by it's base class SPItem
in the method (like ID for instance), tools like Resharper will recommend to use the base type as the parameter.
Even though the actual object passed is an SPListItem
, the method it's passed to only "needs to know" about the the base type's properties as it won't use anything from the actual derived class, thus generalizing your code.
-
What are the benefits of generalizing your code by only passing it the SPItem rather then the SPListItem? Commented Aug 13, 2011 at 0:52
-
1It would be useful if you have a list of objects that all inherit from SPItem and you wanted to loop through them and call one of the methods that is implemented in SPItem. Commented Aug 13, 2011 at 17:28