1

Imagine I have have a struct with 9 properties, which return a value type as its result and in that struct I also have a property which returns a reference type : IEnumerable like this:

public IEnumerable<KeyValuePair<String, String>> Dostuff
        {
            get
            {
                //doing some operations in here
                return _valueToReturn;
            }
        }

Using IEnumerable will require heap space, but actually the struct is based on the stack, so what to do in my case?

By the way the struct is immutable.

trincot
  • 317,000
  • 35
  • 244
  • 286
kkkk00999
  • 179
  • 2
  • 13
  • 2
    You don't care. The CLR takes care of all this stuff for you. – Matthew Watson Apr 14 '16 at 10:49
  • https://msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspx – Nahum Apr 14 '16 at 10:53
  • "but actually the struct is based on the stack" is a little incorrect, this should be "value types _can_ be stored on the stack". It's quite possible that any value type could be stored in the heap too. Let the CLR care about that though. More information [in a blog by Eric Lippert](https://blogs.msdn.microsoft.com/ericlippert/2010/09/30/the-truth-about-value-types/) – Stephen Ross Apr 14 '16 at 10:56
  • if in doubt, its a class. This has got to be a duplicate – Jodrell Apr 14 '16 at 11:01
  • Unless you are going to have zillions of instances don't care about it. http://blog.codinghorror.com/the-sad-tragedy-of-micro-optimization-theater/ – Ignacio Soler Garcia Apr 14 '16 at 11:17

2 Answers2

0

There's a page that shows how to choose between struct and class.

As I understand, if the total size of all fields in the struct is less than 16 bytes, keeping it as struct is better than changing it to class. The number of properties doesn't matter.

DRKblade
  • 347
  • 2
  • 13
0

In your case, declare the type as a class.

If you don't know, or are not sure, define the type as a class.

If the type is a small aggregation of primitive types then a struct might offer better performance. However, the benefits are smaller than the risks so, unless you are sure use a class.

So then, how can you be sure, try it and measure the performance with representative data, on representative hardware, compiled in release mode etc. etc. If you really care about performance you'll have to do this anyway.

If you don't want to do this, use a class.

Jodrell
  • 34,946
  • 5
  • 87
  • 124