" but not inside "typeof ()"? SA1125 : UseShorthandForNullableTypes has this description (taken from t...">

SA1125: why use "int?" unlike "Nullable <int>" but not inside "typeof ()"?

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

Forces the use of a shorthand string of type NULL, not Nullable<T> , except inside typeof() .

Is there a reason why it has an exception for the typeof() operator? typeof(int?) compiles just as well, is it just the preference of StyleCop authors, or is there more in-depth reasoning?

Edit : since the official documentation does not mention this exception, I checked 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 warning SA1125.

Edit 2 : Work item for StyleCop that needs to fix this behavior

+6
source share
2 answers

My opinion is that this is most likely a mistake, at least a missed behavior. The code indicates:

 // 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)) { 

It looks like it is trying to support Nullable<> inside typeof(Nullable<>) . However, checking for TypeofExpression inadvertently filters out closed generics for no apparent reason.

Find CheckShorthandForNullableTypes :

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

0
source

Although I really do not know the reason (since I am not the developer of this rule), I suspect that it is designed so as not to generate a warning for this particular use of typeof :

 typeof(Nullable<>) 

Speaking that this is the real official reason, they may have a hardcode exception for this particular use instead of writing an exception for all using typeof(Nullable<X>) .

Please note that all these are only assumptions.


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, they basically look for longhand generic types and handle the special Nullable<> case, which they resolve because there are no abbreviations available for it . AFAIK, Nullable<> only makes sense in the context of typeof() , so I assume they made an exception for this case.

+3
source

All Articles