Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

stylecop

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

like image 913
Knaģis Avatar asked Apr 22 '13 11:04

Knaģis


1 Answers

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.

like image 139
ken2k Avatar answered Oct 13 '22 11:10

ken2k