Why can't Nullable <int> compile but int? does without using a system;

In .Net 2 code:

namespace ns { class Class1 { Nullable<int> a; } } 

does not compile and does not give an error:

Cannot find the name of the type or namespace Nullable (are you missing the using directive or assembly references?)

Missing using System; but this code:

 namespace ns { class Class1 { int? a; } } 

compiles.

Can someone explain why?

+4
source share
3 answers

I believe int? is an alias for

 System.Nullable<System.Int32> 

Since the full type name is specified, there is no reason to add a using directive.

+7
source

Syntax T? it is converted by the compiler to System.Nullable<T> by directly calling the type, and not by examining using , which are in scope. You could also write this and the compiler will succeed:

 System.Nullable<int> a; 
+11
source

? this is a language construct, and System.Nullable is a class - since it lives in the System namespace, you need to import it into a file (or, most often, explicitly import it for the entire project as part of the project’s properties / configuration).

+2
source

All Articles