<p>What's the difference between struct and class in .NET?</p>

[{'answer_id': 13051, 'author': 'Ed S.', 'author_id': 1053, 'author_profile': 'https://Stackoverflow.com/users/1053', 'pm_score': 4, 'selected': False, 'text': '<p>Well, for starters, a struct is passed by value rather than by reference.  Structs are good for relatively simple data structures, while classes have a lot more flexibility from an architectural point of view via polymorphism and inheritance.</p>\n\n<p>Others can probably give you more detail than I, but I use structs when the structure that I am going for is simple.</p>\n'}, {'answer_id': 13053, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 6, 'selected': False, 'text': '<p>In .NET the struct and class declarations differentiate between reference types and value types.</p>\n\n<p>When you pass round a reference type there is only one actually stored.  All the code that accesses the instance is accessing the same one.</p>\n\n<p>When you pass round a value type each one is a copy. All the code is working on its own copy.</p>\n\n<p>This can be shown with an example:</p>\n\n<pre><code>struct MyStruct \n{\n    string MyProperty { get; set; }\n}\n\nvoid ChangeMyStruct(MyStruct input) \n{ \n   input.MyProperty = "new value";\n}\n\n...\n\n// Create value type\nMyStruct testStruct = new MyStruct { MyProperty = "initial value" }; \n\nChangeMyStruct(testStruct);\n\n// Value of testStruct.MyProperty is still "initial value"\n// - the method changed a new copy of the structure.\n</code></pre>\n\n<p>For a class this would be different</p>\n\n<pre><code>class MyClass \n{\n    string MyProperty { get; set; }\n}\n\nvoid ChangeMyClass(MyClass input) \n{ \n   input.MyProperty = "new value";\n}\n\n...\n\n// Create reference type\nMyClass testClass = new MyClass { MyProperty = "initial value" };\n\nChangeMyClass(testClass);\n\n// Value of testClass.MyProperty is now "new value" \n// - the method changed the instance passed.\n</code></pre>\n\n<p>Classes can be nothing - the reference can point to a null.</p>\n\n<p>Structs are the actual value - they can be empty but never null. For this reason structs always have a default constructor with no parameters - they need a \'starting value\'.</p>\n'}, {'answer_id': 13102, 'author': 'Zooba', 'author_id': 891, 'author_profile': 'https://Stackoverflow.com/users/891', 'pm_score': 4, 'selected': False, 'text': '<p>Instances of classes are stored on the managed heap. All variables \'containing\' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.</p>\n\n<p>Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.</p>\n\n<p>The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.</p>\n'}, {'answer_id': 13132, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>Structs are the actual value - they can be empty but never null</p>\n</blockquote>\n\n<p>This is true, however also note that as of .NET 2 structs support a Nullable version and C# supplies some syntactic sugar to make it easier to use.</p>\n\n<pre><code>int? value = null;\nvalue  = 1;\n</code></pre>\n'}, {'answer_id': 13275, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 11, 'selected': True, 'text': '<p>In .NET, there are two categories of types, <em>reference types</em> and <em>value types</em>.</p>\n\n<p>Structs are <em>value types</em> and classes are <em>reference types</em>.</p>\n\n<p>The general difference is that a <em>reference type</em> lives on the heap, and a <em>value type</em> lives inline, that is, wherever it is your variable or field is defined.</p>\n\n<p>A variable containing a <em>value type</em> contains the entire <em>value type</em> value. For a struct, that means that the variable contains the entire struct, with all its fields.</p>\n\n<p>A variable containing a <em>reference type</em> contains a pointer, or a <em>reference</em> to somewhere else in memory where the actual value resides.</p>\n\n<p>This has one benefit, to begin with:</p>\n\n<ul>\n<li><em>value types</em> always contains a value</li>\n<li><em>reference types</em> can contain a <em>null</em>-reference, meaning that they don\'t refer to anything at all at the moment</li>\n</ul>\n\n<p>Internally, <em>reference type</em>s are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:</p>\n\n<ul>\n<li>copying the contents of a <em>value type</em> variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won\'t affect the other</li>\n<li>copying the contents of a <em>reference type</em> variable into another variable, copies the reference, which means you now have two references to the same <em>somewhere else</em> storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you\'re really just looking at the same data both places</li>\n</ul>\n\n<p>When you declare variables or fields, here\'s how the two types differ:</p>\n\n<ul>\n<li>variable: <em>value type</em> lives on the stack, <em>reference type</em> lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note <a href="https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/" rel="noreferrer">Eric Lipperts article series: The Stack Is An Implementation Detail</a>.)</li>\n<li>class/struct-field: <em>value type</em> lives completely inside the type, <em>reference type</em> lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.</li>\n</ul>\n'}, {'answer_id': 171090, 'author': 'Thomas Bratt', 'author_id': 15985, 'author_profile': 'https://Stackoverflow.com/users/15985', 'pm_score': 8, 'selected': False, 'text': "<p>A short summary of each:</p>\n\n<p><strong>Classes Only:</strong></p>\n\n<ul>\n<li>Can support inheritance</li>\n<li>Are reference (pointer) types</li>\n<li>The reference can be null</li>\n<li>Have memory overhead per new instance</li>\n</ul>\n\n<p><strong>Structs Only:</strong></p>\n\n<ul>\n<li>Cannot support inheritance</li>\n<li>Are value types</li>\n<li>Are passed by value (like integers)</li>\n<li>Cannot have a null reference (unless Nullable is used)</li>\n<li>Do not have a memory overhead per new instance - unless 'boxed'</li>\n</ul>\n\n<p><strong>Both Classes and Structs:</strong></p>\n\n<ul>\n<li>Are compound data types typically used to contain a few variables that have some logical relationship</li>\n<li>Can contain methods and events</li>\n<li>Can support interfaces</li>\n</ul>\n"}, {'answer_id': 1686098, 'author': 'Swagatika dhal', 'author_id': 204597, 'author_profile': 'https://Stackoverflow.com/users/204597', 'pm_score': 4, 'selected': False, 'text': "<p><strong>Structure vs Class</strong></p>\n\n<p>A structure is a value type so it is stored on the stack, but a class is a reference type and is stored on the heap.</p>\n\n<p>A structure doesn't support inheritance, and polymorphism, but a class supports both.</p>\n\n<p>By default, all the struct members are public but class members are by default private in nature.</p>\n\n<p>As a structure is a value type, we can't assign null to a struct object, but it is not the case for a class.</p>\n"}, {'answer_id': 6812085, 'author': 'Zain Ali', 'author_id': 538789, 'author_profile': 'https://Stackoverflow.com/users/538789', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li><p>Events declared in a class have their += and -= access automatically locked via a lock(this) to make them thread safe (static events are locked on the typeof the class). Events declared in a struct do not have their += and -= access automatically locked. A lock(this) for a struct would not work since you can only lock on a reference type expression.</p></li>\n<li><p>Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.</p></li>\n<li><p>A struct always has a built-in public default constructor.</p>\n\n<pre><code>class DefaultConstructor\n{\n    static void Eg()\n    {\n        Direct     yes = new   Direct(); // Always compiles OK\n        InDirect maybe = new InDirect(); // Compiles if constructor exists and is accessible\n        //...\n    }\n}\n</code></pre>\n\n<p>This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.</p>\n\n<pre><code>class NonInstantiable\n{\n    private NonInstantiable() // OK\n    {\n    }\n}\n\nstruct Direct\n{\n    private Direct() // Compile-time error\n    {\n    }\n}\n</code></pre></li>\n<li><p>A struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.</p>\n\n<pre><code>struct Direct\n{\n    ~Direct() {} // Compile-time error\n}\nclass InDirect\n{\n    ~InDirect() {} // Compiles OK\n}\n\nAnd the CIL for ~Indirect() looks like this:\n\n.method family hidebysig virtual instance void\n        Finalize() cil managed\n{\n  // ...\n} // end of method Indirect::Finalize\n</code></pre></li>\n<li><p>A struct is implicitly sealed, a class isn't. <br/>\nA struct can't be abstract, a class can. <br/>\nA struct can't call : base() in its constructor whereas a class with no explicit base class can. <br/>\nA struct can't extend another class, a class can. <br/>\nA struct can't declare protected members (for example, fields, nested types) a class can. <br/>\nA struct can't declare abstract function members, an abstract class can. <br/>\nA struct can't declare virtual function members, a class can. <br/>\nA struct can't declare sealed function members, a class can. <br/>\nA struct can't declare override function members, a class can. <br/>\nThe one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString(). <br/></p></li>\n</ol>\n"}, {'answer_id': 8350185, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 1, 'selected': False, 'text': "<p>Every variable or field of a primitive value type or structure type holds a unique instance of that type, including all its fields (public and private). By contrast, variables or fields of reference types may hold null, or may refer to an object, stored elsewhere, to which any number of other references may also exist. The fields of a struct will be stored in the same place as the variable or field of that structure type, which may be either on the stack or may be <em>part of</em> another heap object. </p>\n\n<p>Creating a variable or field of a primitive value type will create it with a default value; creating a variable or field of a structure type will create a new instance, creating all fields therein in the default manner.  Creating a new <em>instance</em> of a reference type will start by creating all fields therein in the default manner, and then running optional additional code depending upon the type.</p>\n\n<p>Copying one variable or field of a primitive type to another will copy the value. Copying one variable or field of structure type to another will copy all the fields (public and private) of the former instance to the latter instance. Copying one variable or field of reference type to another will cause the latter to refer to the same instance as the former (if any).</p>\n\n<p>It's important to note that in some languages like C++, the semantic behavior of a type is independent of how it is stored, but that isn't true of .NET. If a type implements mutable value semantics, copying one variable of that type to another copies the properties of the first to another instance, referred to by the second, and using a member of the second to mutate it will cause that second instance to be changed, but not the first. If a type implements mutable reference semantics, copying one variable to another and using a member of the second to mutate the object will affect the object referred to by the first variable; types with immutable semantics do not allow mutation, so it doesn't matter semantically whether copying creates a new instance or creates another reference to the first.</p>\n\n<p>In .NET, it is possible for value types to implement any of the above semantics, provided that all of their fields can do likewise. A reference type, however, can only implement mutable reference semantics or immutable semantics; value types with fields of mutable reference types are limited to either implementing mutable reference semantics or weird hybrid semantics.</p>\n"}, {'answer_id': 11037876, 'author': 'Venkat', 'author_id': 1064638, 'author_profile': 'https://Stackoverflow.com/users/1064638', 'pm_score': 5, 'selected': False, 'text': '<p>In addition to all differences described in the other answers:</p>\n\n<ol>\n<li>Structs <a href="https://stackoverflow.com/q/333829/1709587">cannot have an explicit parameterless constructor</a> whereas a class can</li>\n<li>Structs <a href="https://stackoverflow.com/q/8276036/1709587">cannot have destructors</a>, whereas a class can</li>\n<li>Structs <a href="https://stackoverflow.com/q/1222935/1709587">can\'t inherit</a> from another struct or class whereas a class can inherit from another class. (Both structs and classes can implement from an interface.)</li>\n</ol>\n\n<p>If you are after a video explaining all the differences, you can check out <em><a href="http://csharp-video-tutorials.blogspot.com/2012/06/part-29-c-tutorial-difference-between.html" rel="noreferrer">Part 29 - C# Tutorial - Difference between classes and structs in C#</a></em>.</p>\n'}, {'answer_id': 23930370, 'author': 'Arijit Mukherjee', 'author_id': 3336204, 'author_profile': 'https://Stackoverflow.com/users/3336204', 'pm_score': 2, 'selected': False, 'text': '<p>Besides the basic difference of access specifier, and few mentioned above I would like to add some of the major differences including few of the mentioned above with a code sample with output, which will give a more clear idea of the reference and value </p>\n\n<p><strong>Structs:</strong> </p>\n\n<ul>\n<li>Are value types and do not require heap allocation.</li>\n<li>Memory allocation is different and is stored in stack</li>\n<li>Useful for small data structures </li>\n<li>Affect performance, when we pass value to method, we pass the entire data structure and all is passed to the stack.</li>\n<li>Constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary</li>\n<li>The variables each have their own copy of the data, and it is not possible for operations on one to affect the other.</li>\n<li>Do not support user-specified inheritance, and they implicitly inherit from type object</li>\n</ul>\n\n<p><strong>Class:</strong></p>\n\n<ul>\n<li>Reference Type value</li>\n<li>Stored in Heap</li>\n<li>Store a reference to a dynamically allocated object</li>\n<li>Constructors are invoked with the new operator, but that does not allocate memory on the heap</li>\n<li>Multiple variables may have a reference to the same object</li>\n<li>It is possible for operations on one variable to affect the object referenced by the other variable</li>\n</ul>\n\n<p><strong>Code Sample</strong></p>\n\n<pre><code>    static void Main(string[] args)\n    {\n        //Struct\n        myStruct objStruct = new myStruct();\n        objStruct.x = 10;\n        Console.WriteLine("Initial value of Struct Object is: " + objStruct.x);\n        Console.WriteLine();\n        methodStruct(objStruct);\n        Console.WriteLine();\n        Console.WriteLine("After Method call value of Struct Object is: " + objStruct.x);\n        Console.WriteLine();\n\n        //Class\n        myClass objClass = new myClass(10);\n        Console.WriteLine("Initial value of Class Object is: " + objClass.x);\n        Console.WriteLine();\n        methodClass(objClass);\n        Console.WriteLine();\n        Console.WriteLine("After Method call value of Class Object is: " + objClass.x);\n        Console.Read();\n    }\n    static void methodStruct(myStruct newStruct)\n    {\n        newStruct.x = 20;\n        Console.WriteLine("Inside Struct Method");\n        Console.WriteLine("Inside Method value of Struct Object is: " + newStruct.x);\n    }\n    static void methodClass(myClass newClass)\n    {\n        newClass.x = 20;\n        Console.WriteLine("Inside Class Method");\n        Console.WriteLine("Inside Method value of Class Object is: " + newClass.x);\n    }\n    public struct myStruct\n    {\n        public int x;\n        public myStruct(int xCons)\n        {\n            this.x = xCons;\n        }\n    }\n    public class myClass\n    {\n        public int x;\n        public myClass(int xCons)\n        {\n            this.x = xCons;\n        }\n    }\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<p>Initial value of Struct Object is: 10</p>\n\n<p>Inside Struct Method\nInside Method value of Struct Object is: 20</p>\n\n<p><strong>After Method call value of Struct Object is: 10</strong></p>\n\n<p>Initial value of Class Object is: 10</p>\n\n<p>Inside Class Method\nInside Method value of Class Object is: 20</p>\n\n<p><strong>After Method call value of Class Object is: 20</strong></p>\n\n<p>Here you can clearly see the difference between call by value and call by reference.</p>\n'}, {'answer_id': 32204716, 'author': 'Will Calderwood', 'author_id': 654070, 'author_profile': 'https://Stackoverflow.com/users/654070', 'pm_score': 4, 'selected': False, 'text': '<p>To add to the other answers, there is one fundamental difference that is worth noting, and that is how the data is stored within arrays as this can have a major effect on performance. </p>\n\n<ul>\n<li>With a struct, the array contains the instance of the struct</li>\n<li>With a class, the array contains a pointer to an instance of the class elsewhere in memory</li>\n</ul>\n\n<p>So an array of structs looks like this in memory</p>\n\n<p><code>[struct][struct][struct][struct][struct][struct][struct][struct]</code></p>\n\n<p>Whereas an array of classes looks like this</p>\n\n<p><code>[pointer][pointer][pointer][pointer][pointer][pointer][pointer][pointer]</code></p>\n\n<p>With an array of classes, the values you\'re interested in are not stored within the array, but elsewhere in memory.</p>\n\n<p>For a vast majority of applications this difference doesn\'t really matter, however, in high performance code this will affect locality of data within memory and have a large impact on the performance of the CPU cache. Using classes when you could/should have used structs will massively increase the number of cache misses on the CPU.</p>\n\n<p>The slowest thing a modern CPU does is not crunching numbers, it\'s fetching data from memory, and an L1 cache hit is many times faster than reading data from RAM.</p>\n\n<p>Here\'s some code you can test. On my machine, iterating through the class array takes ~3x longer than the struct array.</p>\n\n<pre><code>    private struct PerformanceStruct\n    {\n        public int i1;\n        public int i2;\n    }\n\n    private class PerformanceClass\n    {\n        public int i1;\n        public int i2;\n    }\n\n    private static void DoTest()\n    {\n        var structArray = new PerformanceStruct[100000000];\n        var classArray = new PerformanceClass[structArray.Length];\n\n        for (var i = 0; i &lt; structArray.Length; i++)\n        {\n            structArray[i] = new PerformanceStruct();\n            classArray[i] = new PerformanceClass();\n        }\n\n        long total = 0;\n        var sw = new Stopwatch();\n        sw.Start();\n        for (var loops = 0; loops &lt; 100; loops++)\n        for (var i = 0; i &lt; structArray.Length; i++)\n        {\n            total += structArray[i].i1 + structArray[i].i2;\n        }\n\n        sw.Stop();\n        Console.WriteLine($"Struct Time: {sw.ElapsedMilliseconds}");\n        sw = new Stopwatch();\n        sw.Start();\n        for (var loops = 0; loops &lt; 100; loops++)\n        for (var i = 0; i &lt; classArray.Length; i++)\n        {\n            total += classArray[i].i1 + classArray[i].i2;\n        }\n\n        Console.WriteLine($"Class Time: {sw.ElapsedMilliseconds}");\n    }\n</code></pre>\n'}, {'answer_id': 32738451, 'author': 'kb9', 'author_id': 5019390, 'author_profile': 'https://Stackoverflow.com/users/5019390', 'pm_score': 3, 'selected': False, 'text': '<p>As previously mentioned: Classes are reference type while Structs are value types with all the consequences.</p>\n\n<p>As a thumb of rule Framework Design Guidelines recommends using Structs instead of classes if: </p>\n\n<ul>\n<li>It has an instance size under 16 bytes</li>\n<li>It logically represents a single value, similar to primitive types (int, double, etc.)</li>\n<li>It is immutable</li>\n<li>It will not have to be boxed frequently</li>\n</ul>\n'}, {'answer_id': 43968259, 'author': 'SunsetQuest', 'author_id': 2352507, 'author_profile': 'https://Stackoverflow.com/users/2352507', 'pm_score': 5, 'selected': False, 'text': '<p>From Microsoft\'s <a href="https://msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspx" rel="noreferrer">Choosing Between Class and Struct</a> ...</p>\n\n<blockquote>\n  <p>As a rule of thumb, the majority of types in a framework should be\n  classes. There are, however, some situations in which the\n  characteristics of a value type make it more appropriate to use\n  structs.</p>\n  \n  <p><strong>✓</strong> <strong>CONSIDER a struct</strong> instead of a class:</p>\n  \n  <ul>\n  <li>If instances of the type are small and commonly short-lived or are commonly embedded in other objects.</li>\n  </ul>\n  \n  <p><strong>X</strong> <strong>AVOID a struct</strong> unless the type has <strong>all</strong> of the following\n  characteristics:</p>\n  \n  <ul>\n  <li>It logically represents a single value, similar to primitive types    (int, double, etc.). </li>\n  <li>It has an instance size under 16 bytes. </li>\n  <li>It is immutable. <em>(cannot be changed)</em></li>\n  <li>It will not have to be boxed frequently.</li>\n  </ul>\n</blockquote>\n'}, {'answer_id': 45462416, 'author': 'Ning', 'author_id': 8360058, 'author_profile': 'https://Stackoverflow.com/users/8360058', 'pm_score': 3, 'selected': False, 'text': "<p>Just to make it complete, there is another difference when using the <code>Equals</code> method, which is inherited by all classes and structures. </p>\n\n<p>Lets's say we have a class and a structure:</p>\n\n<pre><code>class A{\n  public int a, b;\n}\nstruct B{\n  public int a, b;\n}\n</code></pre>\n\n<p>and in the Main method, we have 4 objects.</p>\n\n<pre><code>static void Main{\n  A c1 = new A(), c2 = new A();\n  c1.a = c1.b = c2.a = c2.b = 1;\n  B s1 = new B(), s2 = new B();\n  s1.a = s1.b = s2.a = s2.b = 1;\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>s1.Equals(s2) // true\ns1.Equals(c1) // false\nc1.Equals(c2) // false\nc1 == c2 // false\n</code></pre>\n\n<p><strong>So</strong>, structures are suited for numeric-like objects, like points (save x and y coordinates). And classes are suited for others. Even if 2 people have same name, height, weight..., they are still 2 people. </p>\n"}, {'answer_id': 47864451, 'author': 'Roman Pokrovskij', 'author_id': 506147, 'author_profile': 'https://Stackoverflow.com/users/506147', 'pm_score': 2, 'selected': False, 'text': '<p>There is one interesting case of "class vs struct" puzzle - situation when you need to return several results from the method: choose which to use. If you know the  ValueTuple story - you know that ValueTuple (struct) was added because it should  be more effective then Tuple (class). But what does it mean in numbers? Two tests: one is struct/class that have 2 fields, other with struct/class that have 8 fields (with dimension more then 4 - class should become more effective then struct in terms processor ticks, but of course GC load also should be considered).</p>\n\n<p>P.S. Another benchmark for specific case \'sturct or class with collections\' is there: <a href="https://stackoverflow.com/a/45276657/506147">https://stackoverflow.com/a/45276657/506147</a></p>\n\n<pre><code>BenchmarkDotNet=v0.10.10, OS=Windows 10 Redstone 2 [1703, Creators Update] (10.0.15063.726)\nProcessor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4\nFrequency=3233540 Hz, Resolution=309.2586 ns, Timer=TSC\n.NET Core SDK=2.0.3\n  [Host] : .NET Core 2.0.3 (Framework 4.6.25815.02), 64bit RyuJIT\n  Clr    : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2115.0\n  Core   : .NET Core 2.0.3 (Framework 4.6.25815.02), 64bit RyuJIT\n\n\n            Method |  Job | Runtime |     Mean |     Error |    StdDev |      Min |      Max |   Median | Rank |  Gen 0 | Allocated |\n------------------ |----- |-------- |---------:|----------:|----------:|---------:|---------:|---------:|-----:|-------:|----------:|\n  TestStructReturn |  Clr |     Clr | 17.57 ns | 0.1960 ns | 0.1834 ns | 17.25 ns | 17.89 ns | 17.55 ns |    4 | 0.0127 |      40 B |\n   TestClassReturn |  Clr |     Clr | 21.93 ns | 0.4554 ns | 0.5244 ns | 21.17 ns | 23.26 ns | 21.86 ns |    5 | 0.0229 |      72 B |\n TestStructReturn8 |  Clr |     Clr | 38.99 ns | 0.8302 ns | 1.4097 ns | 37.36 ns | 42.35 ns | 38.50 ns |    8 | 0.0127 |      40 B |\n  TestClassReturn8 |  Clr |     Clr | 23.69 ns | 0.5373 ns | 0.6987 ns | 22.70 ns | 25.24 ns | 23.37 ns |    6 | 0.0305 |      96 B |\n  TestStructReturn | Core |    Core | 12.28 ns | 0.1882 ns | 0.1760 ns | 11.92 ns | 12.57 ns | 12.30 ns |    1 | 0.0127 |      40 B |\n   TestClassReturn | Core |    Core | 15.33 ns | 0.4343 ns | 0.4063 ns | 14.83 ns | 16.44 ns | 15.31 ns |    2 | 0.0229 |      72 B |\n TestStructReturn8 | Core |    Core | 34.11 ns | 0.7089 ns | 1.4954 ns | 31.52 ns | 36.81 ns | 34.03 ns |    7 | 0.0127 |      40 B |\n  TestClassReturn8 | Core |    Core | 17.04 ns | 0.2299 ns | 0.2150 ns | 16.68 ns | 17.41 ns | 16.98 ns |    3 | 0.0305 |      96 B |\n</code></pre>\n\n<p>Code test:</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Attributes.Columns;\nusing BenchmarkDotNet.Attributes.Exporters;\nusing BenchmarkDotNet.Attributes.Jobs;\nusing DashboardCode.Routines.Json;\n\nnamespace Benchmark\n{\n    //[Config(typeof(MyManualConfig))]\n    [RankColumn, MinColumn, MaxColumn, StdDevColumn, MedianColumn]\n    [ClrJob, CoreJob]\n    [HtmlExporter, MarkdownExporter]\n    [MemoryDiagnoser]\n    public class BenchmarkStructOrClass\n    {\n        static TestStruct testStruct = new TestStruct();\n        static TestClass testClass = new TestClass();\n        static TestStruct8 testStruct8 = new TestStruct8();\n        static TestClass8 testClass8 = new TestClass8();\n        [Benchmark]\n        public void TestStructReturn()\n        {\n            testStruct.TestMethod();\n        }\n\n        [Benchmark]\n        public void TestClassReturn()\n        {\n            testClass.TestMethod();\n        }\n\n\n        [Benchmark]\n        public void TestStructReturn8()\n        {\n            testStruct8.TestMethod();\n        }\n\n        [Benchmark]\n        public void TestClassReturn8()\n        {\n            testClass8.TestMethod();\n        }\n\n        public class TestStruct\n        {\n            public int Number = 5;\n            public struct StructType&lt;T&gt;\n            {\n                public T Instance;\n                public List&lt;string&gt; List;\n            }\n\n            public int TestMethod()\n            {\n                var s = Method1(1);\n                return s.Instance;\n            }\n\n            private StructType&lt;int&gt; Method1(int i)\n            {\n                return Method2(++i);\n            }\n\n            private StructType&lt;int&gt; Method2(int i)\n            {\n                return Method3(++i);\n            }\n\n            private StructType&lt;int&gt; Method3(int i)\n            {\n                return Method4(++i);\n            }\n\n            private StructType&lt;int&gt; Method4(int i)\n            {\n                var x = new StructType&lt;int&gt;();\n                x.List = new List&lt;string&gt;();\n                x.Instance = ++i;\n                return x;\n            }\n        }\n\n        public class TestClass\n        {\n            public int Number = 5;\n            public class ClassType&lt;T&gt;\n            {\n                public T Instance;\n                public List&lt;string&gt; List;\n            }\n\n            public int TestMethod()\n            {\n                var s = Method1(1);\n                return s.Instance;\n            }\n\n            private ClassType&lt;int&gt; Method1(int i)\n            {\n                return Method2(++i);\n            }\n\n            private ClassType&lt;int&gt; Method2(int i)\n            {\n                return Method3(++i);\n            }\n\n            private ClassType&lt;int&gt; Method3(int i)\n            {\n                return Method4(++i);\n            }\n\n            private ClassType&lt;int&gt; Method4(int i)\n            {\n                var x = new ClassType&lt;int&gt;();\n                x.List = new List&lt;string&gt;();\n                x.Instance = ++i;\n                return x;\n            }\n        }\n\n        public class TestStruct8\n        {\n            public int Number = 5;\n            public struct StructType&lt;T&gt;\n            {\n                public T Instance1;\n                public T Instance2;\n                public T Instance3;\n                public T Instance4;\n                public T Instance5;\n                public T Instance6;\n                public T Instance7;\n                public List&lt;string&gt; List;\n            }\n\n            public int TestMethod()\n            {\n                var s = Method1(1);\n                return s.Instance1;\n            }\n\n            private StructType&lt;int&gt; Method1(int i)\n            {\n                return Method2(++i);\n            }\n\n            private StructType&lt;int&gt; Method2(int i)\n            {\n                return Method3(++i);\n            }\n\n            private StructType&lt;int&gt; Method3(int i)\n            {\n                return Method4(++i);\n            }\n\n            private StructType&lt;int&gt; Method4(int i)\n            {\n                var x = new StructType&lt;int&gt;();\n                x.List = new List&lt;string&gt;();\n                x.Instance1 = ++i;\n                return x;\n            }\n        }\n\n        public class TestClass8\n        {\n            public int Number = 5;\n            public class ClassType&lt;T&gt;\n            {\n                public T Instance1;\n                public T Instance2;\n                public T Instance3;\n                public T Instance4;\n                public T Instance5;\n                public T Instance6;\n                public T Instance7;\n                public List&lt;string&gt; List;\n            }\n\n            public int TestMethod()\n            {\n                var s = Method1(1);\n                return s.Instance1;\n            }\n\n            private ClassType&lt;int&gt; Method1(int i)\n            {\n                return Method2(++i);\n            }\n\n            private ClassType&lt;int&gt; Method2(int i)\n            {\n                return Method3(++i);\n            }\n\n            private ClassType&lt;int&gt; Method3(int i)\n            {\n                return Method4(++i);\n            }\n\n            private ClassType&lt;int&gt; Method4(int i)\n            {\n                var x = new ClassType&lt;int&gt;();\n                x.List = new List&lt;string&gt;();\n                x.Instance1 = ++i;\n                return x;\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 48106205, 'author': 'Shanaka Rathnayaka', 'author_id': 2135103, 'author_profile': 'https://Stackoverflow.com/users/2135103', 'pm_score': 6, 'selected': False, 'text': "<p>Difference between Structs and Classes:</p>\n<ul>\n<li><strong>Struct are value types</strong> whereas <strong>Classes are reference types</strong>.</li>\n<li><strong>Structs are stored on the stack</strong> whereas <strong>Classes are stored on the\nheap</strong>.</li>\n<li>Value types hold their value in memory where they are declared, but a\nreference type holds a reference to an object in memory.</li>\n<li><strong>Value types are destroyed immediately</strong> after the scope is lost whereas\nreference type only destroys the variable after the scope is lost. The object is later destroyed by the garbage collector.</li>\n<li>When you copy a struct into another struct, a new copy of that struct\ngets created. The modified struct won't affect the value of the\nother struct.</li>\n<li>When you copy a class into another class, it only copies the\nreference variable.</li>\n<li>Both reference variables point to the same object on the heap.\nChanges done to one variable will affect the other reference variable.</li>\n<li><strong>Structs can not have destructors</strong>, but classes can have destructors.</li>\n<li><strong>Structs can not have explicit parameter-less constructors</strong> whereas classes can. Structs don't support inheritance, but classes do. Both\nsupport inheritance from an interface.</li>\n<li><strong>Structs are sealed type</strong>.</li>\n</ul>\n"}, {'answer_id': 51536921, 'author': 'Avestura', 'author_id': 7825034, 'author_profile': 'https://Stackoverflow.com/users/7825034', 'pm_score': 5, 'selected': False, 'text': '<div class="s-table-container">\n<table class="s-table">\n<thead>\n<tr>\n<th></th>\n<th>Struct</th>\n<th>Class</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Type</td>\n<td>Value-type</td>\n<td>Reference-type</td>\n</tr>\n<tr>\n<td>Where</td>\n<td>On stack / Inline in containing type</td>\n<td>On Heap</td>\n</tr>\n<tr>\n<td>Deallocation</td>\n<td>Stack unwinds / containing type gets deallocated</td>\n<td>Garbage Collected</td>\n</tr>\n<tr>\n<td>Arrays</td>\n<td>Inline, elements are the actual instances of the value type</td>\n<td>Out of line, elements are just references to instances of the reference type residing on the heap</td>\n</tr>\n<tr>\n<td>Al-Del Cost</td>\n<td>Cheap allocation-deallocation</td>\n<td>Expensive allocation-deallocation</td>\n</tr>\n<tr>\n<td>Memory usage</td>\n<td>Boxed when cast to a reference type or one of the interfaces they implement, <br/> Unboxed when cast back to value type <br/> (Negative impact because boxes are objects that are allocated on the heap and are garbage-collected)</td>\n<td>No boxing-unboxing</td>\n</tr>\n<tr>\n<td>Assignments</td>\n<td>Copy entire data</td>\n<td>Copy the reference</td>\n</tr>\n<tr>\n<td>Change to an instance</td>\n<td>Does not affect any of its copies</td>\n<td>Affect all references pointing to the instance</td>\n</tr>\n<tr>\n<td>Mutability</td>\n<td>Should be immutable</td>\n<td>Mutable</td>\n</tr>\n<tr>\n<td>Population</td>\n<td>In some situations</td>\n<td>Majority of types in a framework should be classes</td>\n</tr>\n<tr>\n<td>Lifetime</td>\n<td>Short-lived</td>\n<td>Long-lived</td>\n</tr>\n<tr>\n<td>Destructor</td>\n<td>Cannot have</td>\n<td>Can have</td>\n</tr>\n<tr>\n<td>Inheritance</td>\n<td>Only from an interface</td>\n<td>Full support</td>\n</tr>\n<tr>\n<td>Polymorphism</td>\n<td>No</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td>Sealed</td>\n<td>Yes</td>\n<td>When have <code>sealed</code> keyword (C#), or <code>Sealed</code> attribute (F#)</td>\n</tr>\n<tr>\n<td>Constructor</td>\n<td>Can not have explicit parameterless constructors</td>\n<td>Any constructor</td>\n</tr>\n<tr>\n<td>Null-assignments</td>\n<td>When marked with nullable question mark</td>\n<td>Yes (When marked with nullable question mark in C# 8+ and F# 5+ <sup>1</sup>)</td>\n</tr>\n<tr>\n<td>Abstract</td>\n<td>No</td>\n<td>When have <code>abstract</code> keyword (C#), or <code>AbstractClass</code> attribute (F#)</td>\n</tr>\n<tr>\n<td>Member Access Modifiers</td>\n<td><code>public</code>, <code>private</code>, <code>internal</code></td>\n<td><code>public</code>, <code>protected</code>, <code>internal</code>, <code>protected internal</code>, <code>private protected</code></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><sup>1</sup> Using <code>null</code> is not encouraged in F#, use <a href="https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/options" rel="noreferrer">Option</a> type instead.</p>\n'}, {'answer_id': 62454991, 'author': 'Arsen Khachaturyan', 'author_id': 806202, 'author_profile': 'https://Stackoverflow.com/users/806202', 'pm_score': 5, 'selected': False, 'text': '<p>I ♥ visualizations, and here I\'ve created a one to show the basic differences between <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct" rel="noreferrer">structs</a> and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes" rel="noreferrer">classes</a>.\n<a href="https://i.stack.imgur.com/M9c18.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M9c18.png" alt="enter image description here" /></a></p>\n<hr />\n<p>And the textual representation just in case ;)</p>\n<pre class="lang-none prettyprint-override"><code>+--------------------------------------------------+------+----------------------------------------------+\n|                      Struct                      |      |                      Class                    |\n+--------------------------------------------------+------+----------------------------------------------+\n| - 1 per Thread.                                  |      | - 1 per application.                         |\n|                                                  |      |                                              |\n| - Holds value types.                             |      | - Holds reference types.                     |\n|                                                  |      |                                              |\n| - Types in the stack are positioned              |      | - No type ordering (data is fragmented).     |\n|   using the LIFO principle.                      |      |                                              |\n|                                                  |      |                                              |\n| - Can\'t have a default constructor and/or        |      | - Can have a default constructor             |\n|   finalizer(destructor).                         |      |   and/or finalizer.                          |\n|                                                  |      |                                              |\n| - Can be created with or without a new operator. |      | - Can be created only with a new operator.   |\n|                                                  |      |                                              |\n| - Can\'t derive from the class or struct          |  VS  | - Can have only one base class and/or        |\n|   but can derive from the multiple interfaces.   |      |   derive from multiple interfaces.           |\n|                                                  |      |                                              |\n| - The data members can\'t be protected.           |      | - Data members can be protected.             |\n|                                                  |      |                                              |\n| - Function members can\'t be                      |      | - Function members can be                    |\n|   virtual or abstract.                           |      |   virtual or abstract.                       |\n|                                                  |      |                                              |\n| - Can\'t have a null value.                       |      | - Can have a null value.                     |\n|                                                  |      |                                              |\n| - During an assignment, the contents are         |      | - Assignment is happening                    |\n|   copied from one variable to another.           |      |   by reference.                              |\n+--------------------------------------------------+------+----------------------------------------------+\n</code></pre>\n<hr />\n<p>For more information look below:</p>\n<ul>\n<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/" rel="noreferrer">Classes and structs</a> (official documentation).</li>\n<li><a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct" rel="noreferrer">Choosing Between Class and Struct</a> (official documentation).</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/13049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905/']