<p>Is it possible in C# to have a Struct with a member variable which is a Class type?  If so, where does the information get stored, on the Stack, the Heap, or both?</p>

[{'answer_id': 68681, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 6, 'selected': True, 'text': '<p>Yes, you can.  The pointer to the class member variable is stored <strike>on the stack</strike> with the rest of the struct\'s values, and the class instance\'s data is stored on the heap.</p>\n\n<p>Structs can also contain class definitions as members (inner classes).</p>\n\n<p>Here\'s some really useless code that at least compiles and runs to show that it\'s possible:</p>\n\n<pre><code>using System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            MyStr m = new MyStr();\n            m.Foo();\n\n            MyStr.MyStrInner mi = new MyStr.MyStrInner();\n            mi.Bar();\n\n            Console.ReadLine();\n        }\n    }\n\n    public class Myclass\n    {\n        public int a;\n    }\n\n    struct MyStr\n    {\n        Myclass mc;\n\n        public void Foo()\n        {\n            mc = new Myclass();\n            mc.a = 1;\n        }\n\n        public class MyStrInner\n        {\n            string x = "abc";\n\n            public string Bar()\n            {\n                return x;\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 68810, 'author': 'Craig Eddy', 'author_id': 5557, 'author_profile': 'https://Stackoverflow.com/users/5557', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s probably not a recommended practice to do so: see <a href="http://msdn.microsoft.com/en-us/library/ms229017(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms229017(VS.85).aspx</a></p>\n\n<blockquote>\n  <p>Reference types are allocated on the heap, and memory management is\n  handled by the garbage collector. </p>\n  \n  <p>Value types are allocated on the stack or inline and are deallocated\n  when they go out of scope. </p>\n  \n  <p>In general, value types are cheaper to allocate and deallocate.\n  However, if they are used in scenarios that require a significant\n  amount of boxing and unboxing, they perform poorly as compared to\n  reference types.</p>\n</blockquote>\n'}, {'answer_id': 6801550, 'author': 'Ben Voigt', 'author_id': 103167, 'author_profile': 'https://Stackoverflow.com/users/103167', 'pm_score': 4, 'selected': False, 'text': "<p>The class content gets stored on the heap.</p>\n\n<p>A reference to the class (which is almost the same as a pointer) gets stored with the struct content.  Where the struct content is stored depends on whether it's a local variable, method parameter, or member of a class, and whether it's been boxed or captured by a closure.</p>\n"}, {'answer_id': 11887584, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 2, 'selected': False, 'text': '<p>If one of the fields of a struct is a class type, that field will either hold the <i>identity</i> of a class object or else a null referece.  If the class object in question is immutable (e.g. <code>string</code>), storing its identity will effectively also store its contents.  If the class object in question is mutable, however, storing the identity will be an effective means of storing the contents <i>if and only if the reference will never fall into the hands of any code which might mutate it once it is stored in the field</i>.</p>\n\n<p>Generally, one should avoid storing mutable class types within a structure unless one of two situations applies:</p>\n\n<ol>\n<li>What one is interested in is, in fact, the identity of the class object rather than its content.  For example, one might define a `FormerControlBounds` structure which holds fields of type `Control` and `Rectangle`, and represents the `Bounds` that control had at some moment in time, for the purpose of being able to later restore the control to its earlier position.  The purpose of the `Control` field would not be to hold a copy of the control\'s state, but rather to identify the control whose position should be restored.  Generally the struct should avoid accessing any mutable members of the object to which it holds a reference, except in cases where it is clear that such access is referring to the current mutable state of the object in question (e.g. in a `CaptureControlPosition` or `RestoreControlToCapturedPosition` method, or a `ControlHasMoved` property).\n<li>The field is `private`, the only methods which read it do so for the purpose of examining its properties without exposing the object itself it to outside code, and the only methods which write it will create a new object, perform all of the mutations that are ever going to happen to it, and then store a reference to that object.  One could, for example, design a `struct` which behaved much like an array, but with value semantics, by having the struct hold an array in a private field, and by having every attempt to write the array create a new array with data from the old one, modify the new array, and store the modified array to that field.  Note that even though the array itself would be a mutable type, every array instance that would ever be stored in the field would be effectively immutable, since it would never be accessible by any code that might mutate it.\n</ol>\n\n<p>Note that scenario #1 is pretty common with generic types; for example, it\'s very common to have a dictionary whose "values" are the identities of mutable objects; enumerating that dictionary will return instances of <code>KeyValuePair</code> whose <code>Value</code> field holds that mutable type.</p>\n\n<p>Scenario #2 is less common.  There is alas no way to tell the compiler that struct methods other than property setters will modify a struct and their use should thus be forbidden in read-only contexts; one could have a struct that behaved like a <code>List&lt;T&gt;</code>, but with value semantics, and included an <code>Add</code> method, but an attempt to call <code>Add</code> on a read-only struct instance would generate bogus code rather than a compiler error.  Further, mutating methods and property setters on such structs will generally perform rather poorly.  Such structs can be useful are when they exist as an immutable wrapper on an otherwise-mutable class; if such a struct is never boxed, performance will often be better than a class.  If boxed exactly once (e.g. by being cast to an interface type), performance will generally be comparable to a class.  If boxed repeatedly, performance can be much worse than a class.</p>\n'}]
['https://Stackoverflow.com/questions/68640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10722/']