<p>I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can't seem to find anything about it.  Is it bad?  Are there unintended consequences of doing so?</p>

<pre><code>public interface Foo { Bar GetBar(); }
public struct Fubar : Foo { public Bar GetBar() { return new Bar(); } }
</code></pre>

[{'answer_id': 63709, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': -1, 'selected': False, 'text': '<p>Structs are just like classes that live in the stack. I see no reason why they should be "unsafe".</p>\n'}, {'answer_id': 63711, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 0, 'selected': False, 'text': '<p>There are no consequences to a struct implementing an interface. For example the built-in system structs implement interfaces like <code>IComparable</code> and <code>IFormattable</code>.</p>\n'}, {'answer_id': 63712, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': "<p>There is very little reason for a value type to implement an interface. Since you cannot subclass a value type, you can always refer to it as its concrete type.</p>\n\n<p>Unless of course, you have multiple structs all implementing the same interface, it might be marginally useful then, but at that point I'd recommend using a class and doing it right.</p>\n\n<p>Of course, by implementing an interface, you are boxing the struct, so it now sits on the heap, and you won't be able to pass it by value anymore...This really reinforces my opinion that you should just use a class in this situation.</p>\n"}, {'answer_id': 63716, 'author': 'Simon Keep', 'author_id': 1127460, 'author_profile': 'https://Stackoverflow.com/users/1127460', 'pm_score': 1, 'selected': False, 'text': '<p>I think the problem is that it causes boxing because structs are value types so there is a slight performance penalty.</p>\n\n<p>This link suggests there might be other issues with it...</p>\n\n<p><a href="http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx</a></p>\n'}, {'answer_id': 63732, 'author': 'dotnetengineer', 'author_id': 8033, 'author_profile': 'https://Stackoverflow.com/users/8033', 'pm_score': 2, 'selected': False, 'text': '<p>Structs are implemented as value types and classes are reference types.  If you have a variable of type Foo, and you store an instance of Fubar in it, it will "Box it" up into a reference type, thus defeating the advantage of using a struct in the first place.</p>\n\n<p>The only reason I see to use a struct instead of a class is because it will be a value type and not a reference type, but the struct can\'t inherit from a class.  If you have the struct inherit an interface, and you pass around interfaces, you lose that value type nature of the struct.  Might as well just make it a class if you need interfaces.</p>\n'}, {'answer_id': 63757, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 7, 'selected': True, 'text': '<p>There are several things going on in this question...</p>\n\n<p>It is possible for a struct to implement an interface, but there are concerns that come about with casting, mutability, and performance. See this post for more details: <a href="https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface" rel="noreferrer">https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface</a></p>\n\n<p>In general, structs should be used for objects that have value-type semantics. By implementing an interface on a struct you can run into boxing concerns as the struct is cast back and forth between the struct and the interface. As a result of the boxing, operations that change the internal state of the struct may not behave properly.</p>\n'}, {'answer_id': 63817, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 2, 'selected': False, 'text': '<p>(Well got nothing major to add but don\'t have editing prowess yet so here goes..)<br>\n<strong>Perfectly Safe. Nothing illegal with implementing interfaces on structs. However you should question why you\'d want to do it.</strong>    </p>\n\n<p>However <strong>obtaining an interface reference to a struct will BOX</strong> it. So performance penalty and so on.   </p>\n\n<p>The only valid scenario which I can think of right now is <a href="https://stackoverflow.com/questions/51526/changing-the-value-of-an-element-in-a-list-of-structs#51585">illustrated in my post here</a>. When you want to modify a struct\'s state stored in a collection, you\'d have to do it via an additional interface exposed on the struct.</p>\n'}, {'answer_id': 1289537, 'author': 'ShuggyCoUk', 'author_id': 12748, 'author_profile': 'https://Stackoverflow.com/users/12748', 'pm_score': 8, 'selected': False, 'text': '<p>Since no one else explicitly provided this answer I will add the following:</p>\n\n<p><strong>Implementing</strong> an interface on a struct has no negative consequences whatsoever.</p>\n\n<p>Any <em>variable</em> of the interface type used to hold a struct will result in a boxed value of that struct being used. If the struct is immutable (a good thing) then this is at worst a performance issue unless you are:</p>\n\n<ul>\n<li>using the resulting object for locking purposes (an immensely bad idea any way)</li>\n<li>using reference equality semantics and expecting it to work for two boxed values from the same struct.</li>\n</ul>\n\n<p>Both of these would be unlikely, instead you are likely to be doing one of the following:</p>\n\n<h3>Generics</h3>\n\n<p>Perhaps many reasonable reasons for structs implementing interfaces is so that they can be used within a <strong>generic</strong> context with <em><a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="noreferrer">constraints</a></em>. When used in this fashion the variable like so:</p>\n\n<pre><code>class Foo&lt;T&gt; : IEquatable&lt;Foo&lt;T&gt;&gt; where T : IEquatable&lt;T&gt;\n{\n    private readonly T a;\n\n    public bool Equals(Foo&lt;T&gt; other)\n    {\n         return this.a.Equals(other.a);\n    }\n}\n</code></pre>\n\n<ol>\n<li>Enable the use of the struct as a type parameter \n\n<ul>\n<li>so long as no other constraint like <code>new()</code> or <code>class</code> is used.</li>\n</ul></li>\n<li>Allow the avoidance of boxing on structs used in this way.</li>\n</ol>\n\n<p>Then this.a is NOT an interface reference thus it does not cause a box of whatever is placed into it. Further when the c# compiler compiles the generic classes and needs to insert invocations of the instance methods defined on instances of the Type parameter T it can use the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.constrained.aspx" rel="noreferrer">constrained</a> opcode:</p>\n\n<blockquote>\n  <p>If thisType is a value type and thisType implements method then ptr is passed unmodified as the \'this\' pointer to a call  method instruction, for the implementation of method by thisType.</p>\n</blockquote>\n\n<p>This avoids the boxing and since the value type is implementing the interface is <em>must</em> implement the method, thus no boxing will occur. In the above example the <code>Equals()</code> invocation is done with no box on this.a<sup>1</sup>.</p>\n\n<h3>Low friction APIs</h3>\n\n<p>Most structs should have primitive-like semantics where bitwise identical values are considered equal<sup>2</sup>. The runtime will supply such behaviour in the implicit <code>Equals()</code> but this can be slow. Also this implicit equality is <em>not</em> exposed as an implementation of <code>IEquatable&lt;T&gt;</code> and thus prevents structs being used easily as keys for Dictionaries unless they explicitly implement it themselves. It is therefore common for many public struct types to declare that they implement <code>IEquatable&lt;T&gt;</code> (where <code>T</code> is them self) to make this easier and better performing as well as consistent with the behaviour of many existing value types within the CLR BCL.</p>\n\n<p>All the primitives in the BCL implement at a minimum: </p>\n\n<ul>\n<li><code>IComparable</code></li>\n<li><code>IConvertible</code></li>\n<li><code>IComparable&lt;T&gt;</code></li>\n<li><code>IEquatable&lt;T&gt;</code> (And thus <code>IEquatable</code>)</li>\n</ul>\n\n<p>Many also implement <code>IFormattable</code>, further many of the System defined value types like DateTime, TimeSpan and Guid implement many or all of these as well. If you are implementing a similarly \'widely useful\' type like a complex number struct or some fixed width textual values then implementing many of these common interfaces (correctly) will make your struct more useful and usable.</p>\n\n<h2>Exclusions</h2>\n\n<p>Obviously if the interface strongly implies <em>mutability</em> (such as <code>ICollection</code>) then implementing it is a bad idea as it would mean tat you either made the struct mutable (leading to the sorts of errors described already where the modifications occur on the boxed value rather than the original) or you confuse users by ignoring the implications of the methods like <code>Add()</code> or throwing exceptions.</p>\n\n<p>Many interfaces do NOT imply mutability (such as <code>IFormattable</code>) and serve as the idiomatic way to expose certain functionality in a consistent fashion. Often the user of the struct will not care about any boxing overhead for such behaviour.</p>\n\n<h2>Summary</h2>\n\n<p>When done sensibly, on immutable value types, implementation of useful interfaces is a good idea</p>\n\n<hr>\n\n<h3>Notes:</h3>\n\n<p>1: Note that the compiler may use this when invoking virtual methods on variables which are <em>known</em> to be of a specific struct type but in which it is required to invoke a virtual method. For example:</p>\n\n<pre><code>List&lt;int&gt; l = new List&lt;int&gt;();\nforeach(var x in l)\n    ;//no-op\n</code></pre>\n\n<p>The enumerator returned by the List is a struct, an optimization to avoid an allocation when enumerating the list (With some interesting <a href="http://www.eggheadcafe.com/software/aspnet/31702392/c-compiler-challenge--s.aspx" rel="noreferrer">consequences</a>). However the semantics of foreach specify that if the enumerator implements <code>IDisposable</code> then <code>Dispose()</code> will be called once the iteration is completed. Obviously having this occur through a boxed call would eliminate any benefit of the enumerator being a struct (in fact it would be worse). Worse, if dispose call modifies the state of the enumerator in some way then this would happen on the boxed instance and many subtle bugs might be introduced in complex cases. Therefore the IL emitted in this sort of situation is:</p>\n\n<pre>\nIL_0001:  newobj      System.Collections.Generic.List..ctor\nIL_0006:  stloc.0     \nIL_0007:  nop         \nIL_0008:  ldloc.0     \nIL_0009:  callvirt    System.Collections.Generic.List.GetEnumerator\nIL_000E:  stloc.2     \nIL_000F:  br.s        IL_0019\nIL_0011:  ldloca.s    02 \nIL_0013:  call        System.Collections.Generic.List.get_Current\nIL_0018:  stloc.1     \nIL_0019:  ldloca.s    02 \nIL_001B:  call        System.Collections.Generic.List.MoveNext\nIL_0020:  stloc.3     \nIL_0021:  ldloc.3     \nIL_0022:  brtrue.s    IL_0011\nIL_0024:  leave.s     IL_0035\nIL_0026:  ldloca.s    02 \nIL_0028:  constrained. System.Collections.Generic.List.Enumerator\nIL_002E:  callvirt    System.IDisposable.Dispose\nIL_0033:  nop         \nIL_0034:  endfinally  \n</pre>\n\n<p>Thus the implementation of IDisposable does not cause any performance issues and the (regrettable) mutable aspect of the enumerator is preserved should the Dispose method actually do anything!  </p>\n\n<p>2: double and float are exceptions to this rule where NaN values are not considered equal.</p>\n'}, {'answer_id': 14322574, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 3, 'selected': False, 'text': '<p>In some cases it may be good for a struct to implement an interface (if it was never useful, it\'s doubtful the creators of .net would have provided for it).  If a struct implements a read-only interface like <code>IEquatable&lt;T&gt;</code>, storing the struct in a storage location (variable, parameter, array element, etc.) of type <code>IEquatable&lt;T&gt;</code> will require that it be boxed (each struct type actually defines two kinds of things: a storage location type which behaves as a value type and a heap-object type which behaves as a class type; the first is implicitly convertible to the second--"boxing"--and the second may be converted to the first via explicit cast--"unboxing").  It is possible to exploit a structure\'s implementation of an interface without boxing, however, using what are called constrained generics.</p>\n\n<p>For example, if one had a method <code>CompareTwoThings&lt;T&gt;(T thing1, T thing2) where T:IComparable&lt;T&gt;</code>, such a method could call <code>thing1.Compare(thing2)</code> without having to box <code>thing1</code> or <code>thing2</code>.  If <code>thing1</code> happens to be, e.g., an <code>Int32</code>, the run-time will know that when it generates the code for <code>CompareTwoThings&lt;Int32&gt;(Int32 thing1, Int32 thing2)</code>.  Since it will know the exact type of both the thing hosting the method and the thing that\'s being passed as a parameter, it won\'t have to box either of them.</p>\n\n<p>The biggest problem with structs that implement interfaces is that a struct which gets stored in a location of interface type, <code>Object</code>, or <code>ValueType</code> (as opposed to a location of its own type) will behave as a class object.  For read-only interfaces this is not generally a problem, but for a mutating interface like <code>IEnumerator&lt;T&gt;</code> it can yield some strange semantics.</p>\n\n<p>Consider, for example, the following code:</p>\n\n<pre><code>List&lt;String&gt; myList = [list containing a bunch of strings]\nvar enumerator1 = myList.GetEnumerator();  // Struct of type List&lt;String&gt;.IEnumerator\nenumerator1.MoveNext(); // 1\nvar enumerator2 = enumerator1;\nenumerator2.MoveNext(); // 2\nIEnumerator&lt;string&gt; enumerator3 = enumerator2;\nenumerator3.MoveNext(); // 3\nIEnumerator&lt;string&gt; enumerator4 = enumerator3;\nenumerator4.MoveNext(); // 4\n</code></pre>\n\n<p>Marked statement #1 will prime <code>enumerator1</code> to read the first element.  The state of that enumerator will be copied to <code>enumerator2</code>.  Marked statement #2 will advance that copy to read the second element, but will not affect <code>enumerator1</code>.  The state of that second enumerator will then be copied to <code>enumerator3</code>, which will be advanced by marked statement #3.  Then, because <code>enumerator3</code> and <code>enumerator4</code> are both reference types, a <em>REFERENCE</em> to <code>enumerator3</code> will then be copied to <code>enumerator4</code>, so marked statement will effectively advance <em>both</em> <code>enumerator3</code> and <code>enumerator4</code>.</p>\n\n<p>Some people try to pretend that value types and reference types are both kinds of <code>Object</code>, but that\'s not really true.  Real value types are convertible to <code>Object</code>, but are not instances of it.  An instance of <code>List&lt;String&gt;.Enumerator</code> which is stored in a location of that type is a value-type and behaves as a value type; copying it to a location of type <code>IEnumerator&lt;String&gt;</code> will convert it to a reference type, and <em>it will behave as a reference type</em>.  The latter is a kind of <code>Object</code>, but the former is not.</p>\n\n<p>BTW, a couple more notes: (1) In general, mutable class types should have their <code>Equals</code> methods test reference equality, but there is no decent way for a boxed struct to do so; (2) despite its name, <code>ValueType</code> is a class type, not a value type; all types derived from <code>System.Enum</code> are value types, as are all types which derive from <code>ValueType</code> with the exception of <code>System.Enum</code>, but both <code>ValueType</code> and <code>System.Enum</code> are class types.</p>\n'}]
['https://Stackoverflow.com/questions/63671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']