Wednesday, September 24, 2003

I've been reviewing a draft of a book on C#, and while reading the author's discussion of struct, I disagreed with the author's criteria for determining whether to declare a class as a class or a struct, which came down to a decision over whether you'll ever want to subclass the type and whether you'll be passing the type as a parameter or returning them from a method.  For the first point, I'm of the opinion that it's really hard to guess whether a class will ever be subclassed, and in any case, I'm not a big fan of sealed classes, so class would win in this case.  Second, I understand the point that you don’t want to kill the stack by passing around large structs, so maybe you don't want to declare a struct with 100 fields, but lots of structs get passed around the FCL – System.Drawing.Point and System.Drawing.Rectangle, are used extensively in System.Windows.Forms, for instance.  Maybe the choice should be class by default, and to use struct as an optimization; at least I’m pretty sure that’s how the FCL authors made the distinction. I don’t know how I’d determine that optimization was necessary; analyze the heap activity maybe? Isn't this a case of trying to outguess the GC?   In any case, you can get around the copying problem for method parameters by declaring them as ref.  I think that most programmers will encounter Value Types by creating their own enums; in 2.5 years of .NET programming, can't remember ever declaring a struct.

3:20:56 PM  permalink Click here to send an email to the editor of this weblog. 


Stories
DateTitle
1/23/2003 Why XML?
8/13/2002 Resolution for IE and Windows problems
8/10/2002 Supporting VS.NET and NAnt
5/11/2002 When do you stop unit testing?
Contact
jabber: weakliem@jabber.org
YM: gweakliem
MSN: gweakliem@pcisys.net
email: Click here to send an email to the editor of this weblog.
Subscribe to "Gordon Weakliem's Weblog" in Radio UserLand.
Click to see the XML version of this web page.