Information Technology Reference
In-Depth Information
Using Nullable User-Defined Types
So far, you have seen nullable forms of the predefined, simple types. You can also create nul-
lable forms of user-defined value types. These bring up additional issues that don't come up
when using the simple types.
The main issue is access to the members of the encapsulated underlying type. A nullable
type doesn't directly expose any of the members of the underlying type. For example, take a
look at the following code and its representation in Figure 23-4. The code declares a struct
called MyStruct , with two public fields.
￿
Since the fields of the struct are public, they can easily be accessed in any instance of the
struct, as shown on the left of the figure.
￿
The nullable version of the struct, however, exposes the underlying type only through
the Value property, and does not directly expose any of its members. Although the mem-
bers are public to the struct, they are not public to the nullable type, as shown on the
right of the figure.
struct MyStruct // Declare a struct.
{
public int x; // Field
public int y; // Field
public MyStruct(int xVal, int yVal) // Constructor
{ x = xVal; y = yVal; }
}
class Program {
static void Main()
{
MyStruct? MSNull = new MyStruct(5, 10) ;
...
Create a temporary instance to initialize the variable.
Figure 23-4. The accessibility of the members of a struct is different from that of the nullable type.
Search WWH ::




Custom Search