Rectangle = null?

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;
 
N

Nicholas Paldino [.NET/C# MVP]

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).
 
O

Olie

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;
 
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;

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
 
O

Olie

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Ternary Operator (?) Question 4
C++ to C# and Nullable 6
Why is this variable NULL? 3
Edit structure members when a property 1
Exception 9
Combobox question 3
is there a bug in RectangleConverter 7
Print Panel 4

Top