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 atypeof()
.
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
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
: