Search code examples
c#stylecop

SA1125: why enforce "int?" as opposed to "Nullable<int>" but not within "typeof()"?


SA1125: UseShorthandForNullableTypes has this description (taken from StyleCop 4.7 settings editor application):

Enforces the use of the shorthand of a nullable type rather than the Nullable<T> except inside a typeof().

Is there a reason why it has the exception for typeof() statement? typeof(int?) compiles just as fine - is this just a preference of StyleCop authors or is there a deeper reasoning?

Edit: since the official documentation does not mention this exception, I tested the following code:

var x = new Nullable<int>();
var y = new int?();
var z = typeof(Nullable<int>);
var v = typeof(int?);

Result: only the first line raises the SA1125 warning.

Edit 2: The work item for StyleCop asking to fix this behavior


Solution

  • My opinion is that this is at most a bug, at least a missed behaviour. The code states:

    // Check the declaration of the generic type for longhand, but allow Nullable<> which has no shorthand
    if (genericType.ChildTokens.Count > 0 && Utils.TokenContainNullable(genericType.ChildTokens.First))
    {
        if (genericType.Parent == null || !(genericType.Parent is TypeofExpression))
        {
    

    Which looks like it is trying to support Nullable<> inside of typeof(Nullable<>). However, the check on TypeofExpression inadvertently filters out closed generics for no apparent reason.

    Look for CheckShorthandForNullableTypes:

    http://stylecop.codeplex.com/SourceControl/changeset/view/249eed5b15ed#Project/Src/AddIns/CSharp/Analyzers/ReadabilityRules.cs