Structs vs. Classes

I’ve never quite been convinced of the value of using structs (pun intended).
Sure, structs are

  • stack allocated instead of heap allocated
  • value types instead of reference types

But that doesn’t really help you when deciding whether to use them or not. And besides, I read somewhere (can’t remember where) that the CLR optimizes heap allocations to the extent that the performance benefit of stack allocated structs is almost negligable over heap allocated “objects” (class instances).

So I’ve largely avoided structs. Today I found an article that kind of vindicates this decision - although for a different reason. It claims (and while I’m not sure of the authority of the author, he/she makes a good case) that structs should not be used because they violate the Principle of Uniformity. You can read it here:

http://www.geocities.com/csharpfaq/structs.html

4 Responses to “Structs vs. Classes”

  1. Lewis E. Moten III Says:

    I’ve had this problem as well. I rarely have a need for a value type. Defining a value type is just like creating a new primative object because of the way they work. int, bool, float, char … they are all primative types and you assign the “value” rather then a “pointer” to other variables.

    If I need the value passed around of my class objects, then I use the Copy method to be sure that I’m not just assigning a pointer to the same piece of memory.

  2. casey Says:

    I have always wondered if I might be missing some really awesome use for structs, since I have almost always end up using classes.

    The only use I’ve found for structs is native/interop, and because MS decided to use them in System.Drawing and a few other places :)

    Perhaps structs could be somehow leveraged inside closures in some clever way (in some language that supports closures).

  3. Stu Says:

    Yeah, I’m with you guys on this. I wonder if someone’s going come along and explain a real-world situation where structs have been the better option? (apart from System.Drawing.Point and it’s ilk :) ) I’ll be sure to post if I find one.

  4. Makiwa » Blog Archive » Structs vs Classes: Revisted Says:

    […] lasses: Revisted Just thought I’d mention Microsoft’s advice on the Structs vs. Classes issue Consider defining a structure instead of a class if in […]

Leave a Reply