SPListItem.Fields.Contains returns true when you don’t think it should!

Firstly, lets explain the scenario where this isn’t working.

Normally I would use the following code snippet to check that a field exists in an SPListItem object.

This usually works really well, except in the following instance. The field is being checked to decide whether a User Interface element should be displayed.

The SPListItem is a content type derived from a Publishing Page Content Type. This content type lives in the /Pages document library along with various other content types.

The user interface element (button) should only display for content types that have a particular field. Unfortunately the button is always displayed as the field check function always return true regardless of the page being displayed.

It took me a while to work this through. Why would a field that is not associated to the page exist? My conclusion was that its because the field existed in the document library, albeit that it was part of another content type.

To workaround this issue, the code was changed from:-




This call now returned false for pages which didn’t have the field associated to their content type. Finally, the user interface element was displayed as it should!