tags:

views:

196

answers:

4

I read that System.Drawing.Point is a value type. I do not understand. Why?

+2  A: 

It's a Structure. Just like DateTime. And structures are value-types.

Pablo Santa Cruz
A: 

Well, I don't specifically know Microsofts reasons, but it makes sense. It is a fixed-size structure containing a small amount of immutable data. I would rather have such a thing allocated on the stack, where it is easy to allocate and easy to free. Making it a class and putting it on the heap means it has to be managed by the GC, which creates a significant amount of overhead for such a trivial thing.

jrista
A: 

In C#, struct types are considered as value types, to allow for user-defined value types. It is the case for Drawing.Point.

RedGlyph
+8  A: 

There are rules that microsoft tries to follow about this, they explain them very well in the MSDN, see Choosing Between Classes and Structures (The book is even better as it had lot of interesting comments)

Even if Point isn't a so good sample of this :

  • Struct should logically represents a single value (In this case a position, even if it have 2 components, but Complex numbers could also be separated in 2 parts and they are prime candidates for being structs)
  • Struct should have an instance size smaller than 16 bytes. (Ok, 2x4=8)
  • Struct should not have to be boxed frequently. (Ok this one is right)
  • BUT, Struct should be immutable (Here is the part where they don't follow their own rules, but i guess that micro-optimization gained over the rules, that anyway were written later)

As i said i guess that the fact that they haven't respected the "immutable" part is both because there weren't rules when System.Drawing was written and for speed as graphic operations could be quite sensitive to this.

I don't know if they were right or not to do it, maybe they measured some common algorithms and found that they lost too much performance in allocating temporary object and copying them over. Anyway such optimizations should only be done after carefully measuring real-world usage of the class/struc.

VirtualBlackFox
About Point is Mutable: not so much an optimization as a concession to the old WIN32 POINT struct.
Henk Holterman
Yes, thanks to point it, i put this in the first version of my answer but removed it as I didn't know if it really was a reason (Anyway even with an immutable struct it will also work, it just make porting old Win32 code more difficult). The only way to know what was exactly the reason for this will be to have someone from Microsoft provide historical informations.
VirtualBlackFox