1

As I'm learning c# I would appreciate some professional advice about structs and classes. As classes are reference types and stored on the heap, while structs are value types and stored on the stack.

What I understand is that structs are typically used for smaller data types for performance reasons.

Given with what I have read, would the following code be a struct or a class.

public struct DisplayWeatherAstronomy
{
    public string SunRise               { get; internal set; }
    public string SunSet                { get; internal set; }
    public string MoonRise              { get; internal set; }
    public string MoonSet               { get; internal set; }
}

/***Extra code***/

Going off two replies, I've added some extra code.

public IEnumerable<DisplayWeatherAstronomy> WeatherAstronomy(string id)
{
    var doc = WeatherXml.XmlData(id);
    var displayAstronomy = (from wd in doc.Descendants("astronomy")
                            select new DisplayWeatherAstronomy
                            {
                                SunRise = (string)wd.Element("sunrise") ?? string.Empty,
                                SunSet = (string)wd.Element("sunset") ?? string.Empty
                            });
    return displayAstronomy;
}
svick
  • 236,525
  • 50
  • 385
  • 514
  • Relevant: http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx and http://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx – It'sNotALie. Jun 15 '13 at 12:41
  • this could be easily a struct simply because i dont see any methods to change the state of the members.you dont need the overhead of a reference type if its this simple. – Prabhu Murthy Jun 15 '13 at 12:45
  • Thanks for the reply, I have added some extra code to try and help me understand – George Phillipson Jun 15 '13 at 13:09
  • possible duplicate of [C# - Garbage Collection](http://stackoverflow.com/questions/8730451/c-sharp-garbage-collection) – JMK Jun 15 '13 at 15:34
  • @JMK That doesn't sound like the same question to me at all. – svick Jun 15 '13 at 17:45
  • @svick I guess duplicate is a bit strong, the question touches on the same topics though and the answer from Eric Lippert is relevant and worth a read. – JMK Jun 15 '13 at 17:49
  • possible duplicate of [When should I use a struct instead of a class?](http://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class) – nawfal Jul 11 '14 at 15:17

3 Answers3

4

This depends more on the purpose of your type than on the size.

If you want to pass data around and want a copy for each call you should use a struct. But if you need to have your data stored at a central location and many other parts of your code should work on the same data, then you need a class. A class is passed by reference and does not duplicate any data.

If you copy data around, as structs do, you can end up with an inconsistent state.

thalm
  • 2,738
  • 2
  • 35
  • 49
  • Actually, passing a `class` around is usually faster than passing a `struct`, because a reference is almost always smaller than the whole `struct`. What's faster is *accessing* the data in a `struct`, because there is one less indirection (and no `null` checking). – svick Jun 15 '13 at 15:33
  • Hi Thalm, thanks for the reply, I'm going to re-read the chapter, as I think I may have misunderstood it. – George Phillipson Jun 15 '13 at 18:04
  • @svick you are right, its not so much about speed, but more about the correct use of the type. – thalm Jun 15 '13 at 21:57
  • @GeorgePhillipson i also vote for my answer as the correct one, because what hans mentioned is specific to your code and does not consider the different use cases of value types vs. reference types. as its explained in detail here: http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx – thalm Jun 15 '13 at 22:00
  • Hi Thalm thanks for the reply, both are good answers, but I can only mark one as correct, that is why I also clicked on the up arrow for your reply, if I could have marked both as correct I would have. – George Phillipson Jun 15 '13 at 22:33
2

First thing you want to do is get your data structure defined correctly. That's an issue with the one you have, it stores times as strings. That's not a great type selection, it is both expensive since you'll need to convert them from the string representation to a time and it painful to make your program work in different locales in the world that have different ways to express a time of day. You definitely want a type that can express a time unambiguously and quickly. A TimeSpan is the correct type for storing a time of the day. It is directly compatible with the DateTime.TimeOfDay property and is stored as a binary value, 64-bits (8 bytes).

Next guidance is that a struct needs to be light-weight to be efficient at runtime. The rule of thumb is that it should not have more than 4 fields and not be larger than 16 bytes. If you exceed those limits then a value type loses its speed advantage. Four fields is good on an x86 processor, it has 4 spare cpu registers than can store values. 16 bytes sets an upper limit on the cost of copying a value when it is passed by value instead of reference.

You're good on the number of fields but exceed the size limit, 4 TimeSpans take 32 bytes. So this should be a class.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Hi Hans thanks for the reply, the reason I chose a string was because the data was in a string format from the remote site. So if I understand you correctly, no more than 4 fields and less than 16 bytes. (Not mentioned in book i'm reading), will be ok for structs, anything bigger will be a class. – George Phillipson Jun 15 '13 at 18:00
  • 1
    You are going to have to convert those strings sooner or later. Sooner is always better. Not in the least because only the code that talks to the web service would have a decent shot at knowing how the string is encoded. – Hans Passant Jun 15 '13 at 18:04
  • Hi Hans true, hopefully going to college in September for HND in computing (Adult Student), books can only teach you so much. I think I learn more reading info on sites like this and posting questions than I do reading books. – George Phillipson Jun 15 '13 at 21:30
0

As classes are reference types and stored on the heap, while structs are value types and stored on the stack.

Wrong.

Given with what I have read, would the following code be a struct or a class.

That would be a bad struct, because it's mutable (even if the setters are internal). In general, at least 95 % of the time you want to use a class. You should create a custom struct when your profiling shows that using a class is slow, and that happens very rarely.

Community
  • 1
  • 1
svick
  • 236,525
  • 50
  • 385
  • 514