Rectangle = null?

  • Thread starter Thread starter Dom
  • Start date Start date
D

Dom

Why can't I say the following;

Rectangle r = null;

The compiler tells me that null is a value type and can't be converted
to Rectangle. But I can't generally set any reference type to null.
For example, I can say:

MyClass c = null;
 
Dom,

I think you mean that you can generally set any reference type to null
(you said can't). This is true, you can assign null to reference type
variables.

However, in this case, the compiler is telling you the truth. Rectangle
is a value type, not a reference type, and you can't assign null to it
(assuming that this is the Rectangle structure from the System.Drawing
namepspace).
 
Why can't I say the following;

Rectangle r = null;

The compiler tells me that null is a value type and can't be converted
to Rectangle. But I can't generally set any reference type to null.
For example, I can say:

MyClass c = null;

A Rectangle is not a class it is a structure and so you can not assign
a null value to it. You should use instead.

Rectangle c = Rectangle.Empty;
 
Why can't I say the following;

Rectangle r = null;

The compiler tells me that null is a value type and can't be converted
to Rectangle. But I can't generally set any reference type to null.
For example, I can say:

MyClass c = null;

Thanks, makes sense now. And Yes, I did mean "I *can* generally ...".

Is there any specific reason why rectangle is a structure, not a
class. And how would I know this from the intellisense window, or is
it just something you learn.

Dom
 
Thanks, makes sense now. And Yes, I did mean "I *can* generally ...".

Is there any specific reason why rectangle is a structure, not a
class. And how would I know this from the intellisense window, or is
it just something you learn.

Dom

Traditionally structures are used instead of classes because they
require less resources. I am not sure if that is the reason here
though. In fact the line between structures and classes is very
blurred in .net.

You can tell if it is a structure and not a class in the intelli-sense
window because it has a slightly different icon.
 
Back
Top