Search code examples
c#sharepointsharepoint-2010content-type

Why should I use fieldLinks when adding fields to a contenttype?


When I search for documentation about creating contenttypes using code (C#) I always find examples using a SPFieldLink to link to an existing field of the site and adding this via

contentType.FieldLinks.Add()

But there is also a method to add fields directly. Is there a good reason why I should not simply add fields using

contentType.Fields.Add(SpField())

?!?

thanks in advance


Solution

  • It might help to look at the XML for a list.

    Here is the XML for the Announcement Content Type:

    <FieldRefs>
        <FieldRef ID="{7662cd2c-f069-4dba-9e35-082cf976e170}" Name="Body" />
        <FieldRef ID="{6a09e75b-8d17-4698-94a8-371eda1af1ac}" Name="Expires" />
    </FieldRefs>
    

    Here is the XML for the Announcement List:

    <Fields>
      <Field ID="{7662cd2c-f069-4dba-9e35-082cf976e170}" Type="Note" RichText="TRUE" RichTextMode="FullHtml" IsolateStyles="TRUE" NumLines="15" Name="Body" DisplayName="$Resources:core,camlid2;" Sortable="FALSE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Body">
      </Field>
      <Field ID="{6a09e75b-8d17-4698-94a8-371eda1af1ac}" Type="DateTime" Name="Expires" DisplayName="$Resources:core,camlid3;" Format="DateOnly" FromBaseType="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Expires">
      </Field>
    </Fields>
    

    Lists have Fields. Content Types have FieldRefs.

    I'm not sure if this is exactly right, but I always describe it as the difference between classes and interfaces or abstract classes. A Content Type is the definition for a list, but, like an interface, it does not contain any data or functionality. Since Fields contain data and functionality, Content Types (disassociated from a list) do not have Fields, they have FieldRefs. YMMV - but that always helps me keep them straight.