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

StackOverflow https://stackoverflow.com/questions/16146157

  •  11-04-2022
  •  | 
  •  

Domanda

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

È stato utile?

Soluzione 2

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

Altri suggerimenti

While I don't actually know the reason (as I'm not the developer of this rule), I suspect it is designed this way to not generate a warning for this specific usage of typeof:

typeof(Nullable<>)

That being said, if this is the actual official reason, they could have hardcode the exception for this particular usage instead of writing an exception for all usages of typeof(Nullable<X>).

Do note that all of this are suppositions only.


EDIT From the source code of Stylecop:

// Check the declaration of the generic type for longhand, but allow Nullable<> which has no shorthand

So from what I understand, the basically search for longhand generic types, and handle the special case of Nullable<> that they allow, because there is no shorthand available for it. AFAIK, Nullable<> only makes sense in the context of typeof(), so I'm guessing they made the exception for this case.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top