Search code examples
c#classstructvalue-typereference-type

Can you have a class in a struct?


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?


Solution

  • Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap.

    Structs can also contain class definitions as members (inner classes).

    Here's some really useless code that at least compiles and runs to show that it's possible:

    using System;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                MyStr m = new MyStr();
                m.Foo();
    
                MyStr.MyStrInner mi = new MyStr.MyStrInner();
                mi.Bar();
    
                Console.ReadLine();
            }
        }
    
        public class Myclass
        {
            public int a;
        }
    
        struct MyStr
        {
            Myclass mc;
    
            public void Foo()
            {
                mc = new Myclass();
                mc.a = 1;
            }
    
            public class MyStrInner
            {
                string x = "abc";
    
                public string Bar()
                {
                    return x;
                }
            }
        }
    }