tags:

views:

69

answers:

2

Apparently you can't have a Nullable<Rectangle> in Silverlight. I'd like to know the technical reasons why not and how many objects this may apply to?

Today I accidentally started a small comment flamewar after stating that the "Rectangle" type was not a Nullable type. That is you can't have a "Nullable<Rectangle>" or a "Rectangle?"

My mistake was in testing it in Silverlight only and assuming that the behaviour of a Silverlight System.Windows.Shapes.Rectangle carried over to the System.Drawing.Rectangle type in .Net. Shame on me. I have since deleted my comments as they added no value to Stack Overflow.

If anyone can answer this question fully it would be much appreciated.

+9  A: 

Nullable<T> can only be used with value types, or structs, and System.Windows.Shapes.Rectangle is a reference type, or class. You don't need to use Nullable<T>, since you can already assign a null reference to a variable of type System.Windows.Shapes.Rectangle:

System.Windows.Shapes.Rectangle rect = null;

By contrast, System.Drawing.Rectangle is a value type, so it cannot have a value of null. The default value is a rectangle of all zeros.

System.Drawing.Rectangle rect = null; // Does not compile
System.Drawing.Rectangle rect = 
    default(System.Drawing.Rectangle); // All fields are zero
Quartermeister
@Quartermeister: So the .Net Rectangle is a simple struct, whereas the Silverlight version requires all the extra UIElement plumbing (which is of course requires it to be an object). Cool. Thanks for that.
Enough already
@HiTech Magic: Perhaps you're looking for System.Windows.Rect?
Bubblewrap
Additionally to this answer, you can place your cursor on the word “Rectangle” (or any other type) and press F12 to find out whether it is a struct or a class. Even better, you can set Visual Studio to colour them differently, which is what I did.
Timwi
A: 

A better answer would be to consider the differences between Option types and Nullable types, which is incidentally covered in the ECMA Standard for Common Language Infrastructure for Generics.

A great explanation of this has already been given for F# on StackOverflow.

So you don't want a Nullable<Rectangle>. You want an Option<Rectangle>.

See MSDN Documentation: Core.Option Module (F#)