Blog Stats
  • Posts - 298
  • Articles - 0
  • Comments - 1352
  • Trackbacks - 0

 

Struct or Class?

Frankly, I haven't seen much use of the struct in the coding libraries I've come across, yet every time I encounter a technical interview, the struct vs class question always seems to come up as a gotcha question.  So for my inaugeral post on the Runtime I would like to quickly point out the difference between these two concepts, and why you may actually want to use a struct instead of a class in your application.

It's all about the memory

The most fundamental difference between a class an a struct is that a class is a reference type and a struct is a value type.  Being a value type means that when a struct is created, it is placed on the stack, while a class is placed on the heap.  Performance-wise, we like things to go on the stack, because the stack is immediately cleaned up when the variables in it go out of scope (ie at the end of the method) whereas the heap requires the Garbage Collector to perform its cleanup.  Realistically though, the .NET framework is optimized such that the performance of one versus the other is likely not going to be a concern for the vast majority of applications (see other authors tirades on not optimizing until you absolutely must).  Also, stack memory is more limited in size than heap memory, but again, realistically this is not a problem you are likely to encounter.

So how else are they different?

For one, you can not create a parameterless constructors!  You must have parameters in your constructors because initializing in the declaration of the field throws an exception in .NET.  Thus if you were to write:

  1. struct MyStruct
  2. {
  3.    public int MyInt = 5;  // Illegal
  4. }

You would get a compiler error.  Instead, a proper struct would look something like this:

  1. struct MyStruct
  2. {
  3.    public int MyInt;
  4.    public int MyInt2;
  5.  
  6.    public MyStruct(int a, int b)
  7.    {
  8.       MyInt = a;
  9.       MyInt2 = b;
  10.    }
  11. }

Of course, you can initialize a static field.

A scenario that might jump up to bite you as a developer is if you forget that structs when passed to a method are passed by value.  If you are used to tossing classes around by reference, changing their data, and having the original object in the caller be updated, you're in for a surprise as the changes you make within the method will be discarded on exit.  You can of course, fix this by using the ref parameter to the method, after you finish cleaning up all the data you corrupted by your omission. :)

Is there any wierdness I should be aware of?

Actually yes.  While you can't inherit a struct class, you actually can implement an interface in a struct class.  This is where the whole memory dynamic changes.  If you cast a struct as its interface type (which you'll likely do, since that's the point of using interfaces after all) then it will be boxed and thrown on the heap.  This would all be well and good, but the wierdness comes in when you realize that any changes to the boxed copy only effect the boxed copy.  So unlike other reference types that you would expect updates to flow through, this particular scenario will not.  So basically if you made a statement like ((MyInterface)MyStruct).DoSomething(); then on the very next line of code checked MyStruct for changes, they wouldn't be there, since the interface call would be boxed, modified, then lost since you didn't explicitly unbox it.

In Conclusion

I rarely use structs in my own code mostly because I've never been faced with a situation where it was compelling.  It is good to know that they exist, however, and the value type/reference type and stack/heap knowledge of how the .NET Framework works is great information to know not only for those gotcha interview questions, but in day to day troubleshooting.

Print posted @ Sunday, November 11, 2007 6:17 AM


Feedback

# re: Struct or Class?

Gravatar

I believe there was a guideline (on MSDN?) that basically boiled down to:

*If* your type requires value equality semantics

*and* is less than 16(?) bytes

*and* you expect a lot of them to be created,

then a struct should be considered.

I think the canonical example is a Point - which fits all 3 of the requirements above.

11/12/2007 6:10 PM | brackett@ufl.edu

# re: Struct or Class?

Gravatar

Excellent point!  I would agree with that statement.  I just don't run into that scenario often.

11/13/2007 5:41 AM | ewise

Post a comment





 

Please add 4 and 7 and type the answer here:

 

 

Copyright © Eric Wise