SPFieldCollection.TryGetFieldByStaticName() is inconsistent

Today’s task required me to check if a column exists on a list, and if not then add it from the site column gallery. Since I knew that SP2010 added a method TryGetList(), I thought I would look around for a similar method for fields.

Sure enough, I found TryGetFieldByStaticName() on the SPFieldCollection class. This is exactly what I was looking for. Why it uses the StaticName property instead of the DisplayName (like the Item method does) or the Internal Name (like CAML does) is totally beyond me. But at least I can check for a field without anticipating an exception.

After hours of digging and bothering people on IM and the twitter, I discovered that TryGetFieldByStaticName() works as you would expect when the SPFieldCollection is based on an SPList object. However, the exact same method based on an SPWeb object (like the site columns gallery) always returns null!

Here is a snippet that illustrates the problem:

private void AddColumnIfNotPresentOnList(SPList list, string columnName)  
{
  SPField listField = null;
  SPField siteField = null;

  listField = list.Fields.TryGetFieldByStaticName(columnName);
  if (listField == null)
  {
    // *** this line always returns null ***
    siteField = list.ParentWeb.Site.RootWeb.
                  Fields.TryGetFieldByStaticName(columnName);

    // had to use the following instead...
    try
    {
      siteField = list.ParentWeb.Site.RootWeb.Fields[columnName];
    }
    catch (Exception)
    {
      // yes, I shudder when writing this code...
    }
    if (siteField != null)
    {
      list.Fields.Add(siteField);
    }
  }
}

* NOTE * The above is an illustration, not working code.

comments powered by Disqus