struct (e.g. int , long , etc.) cannot accept null by default. Thus, .NET provides a generic struct named Nullable<T> , which can be of type T from any other struct s.
public struct Nullable<T> where T : struct {}
It provides a bool HasValue property that indicates whether the current Nullable<T> object has a value; and the T Value property, which receives the value of the current value Nullable<T> (if HasValue == true , otherwise it throws an InvalidOperationException ):
public struct Nullable<T> where T : struct { public bool HasValue { get { } } public T Value { get { if(!HasValue) throw new InvalidOperationException(); return } } }
And finally, in answer to your TypeName? question TypeName? is a shortcut to Nullable<TypeName> .
int? --> Nullable<int> long? --> Nullable<long> bool? --> Nullable<bool>
and in use:
int a = null; // exception. structs -value types- cannot be null int? a = null; // no problem
For example, we have a Table class that generates an HTML <table> in a method called Write . Cm:
public class Table { private readonly int? _width; public Table() { _width = null;
Using the above class - as an example - is something like this:
var output = new OurSampleHtmlWriter();
And we will have:
// output1: <table></table> // output2: <table style="width: 500px;"></table>
source share