6

Is there any reason to prefer SPContentTypeId.Empty over default?

Console.WriteLine(default (SPContentTypeId)); // writes 0x
Console.WriteLine(new SPContentTypeId()); // writes 0x
Console.WriteLine(SPContentTypeId.Empty); // writes 0x00C2208B8CE6E1422CADC1C521EAB2A68B

2 Answers 2

1

SPContentTypeId.Empty is used to indicate and check that a content type has no id (yet), for example, one of the SPContentType constructors

SPContentType(SPContentType parentContentType, SPContentTypeCollection collection, string name)

defined as

public SPContentType(SPContentType parentContentType, SPContentTypeCollection collection, string name) : this(SPContentTypeId.Empty, parentContentType, collection)
{
    this.Initialize(parentContentType, collection, name);
}

or in another method

private SPContentType(SPContentTypeId contentTypeId, SPContentType parentContentType, SPContentTypeCollection cts)

you find code like

if ((parentContentType == null) && contentTypeId.Equals(SPContentTypeId.Empty))
{
    parentContentType = cts.Web.AvailableContentTypes[SPBuiltInContentTypeId.Item];
}
if ((parentContentType == null) && contentTypeId.Equals(SPContentTypeId.Empty))
{
    this.m_id = NewContentTypeId();
}
else if ((parentContentType == null) && !contentTypeId.Equals(SPContentTypeId.Empty))
{
    ...
}

Hope it helps...

0

SPContentTypeId is not a nullable type. Therefore, you cannot initialize an instance of it as null. So instead you can assign it as SPContentTypeId.Empty , which is equivalent to empty content type.

    // SPContentTypeId ctId = null;//Throws build error as not nullable 
    //  SPContentTypeId ctId= string.Empty;//Throws build error as not type is not a string
   SPContentTypeId ctId = SPContentTypeId.Empty;
2
  • You can create struct instance with SPContentTypeId ctId = new SPContentTypeId() and it's not the same as SPContentTypeId.Empty. What are the cases when empty content type comes to play?
    – dbardakov
    Aug 31, 2015 at 15:17
  • I would imagine that Empty would be used to initialize an object prior to code that may not always generate an ID, such as looping through a list of objects containing content type Ids and trying to match one of them. It would be convenient to just check if the ID is still empty, rather than adding a boolean if an ID was found or storing the initial value of SPContentTypeId() and comparing that further along the line.
    – m1g
    Dec 21, 2015 at 5:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.