Note that there are some explanatory texts on larger screens.

plurals
  1. PODeclaring a struct to be returned from an interface method
    primarykey
    data
    text
    <p>I'm writing a method in C# (2.0) that has to return a collection of simple objects. Normally I would do something like this:</p> <pre><code>class MyWidget { struct LittleThing { int foo; DateTime bar; } public IList&lt;LittleThing&gt; LookupThings() { // etc. } } </code></pre> <p>However, I have to declare this method in an interface. The caller doesn't get to see <code>MyWidget</code>, only an <code>IWidget</code> interface. The above setup doesn't work in that situation, because C# does not allow defining types inside an interface. What is the proper or best way to do such a declaration?</p> <p>The straighforward thing I thought of is to simply declare <code>LittleThing</code> outside of the interface. That doesn't seem great, for a couple of reasons. One: it is only ever used by that single method in that single class, so it doesn't seem that <code>LittleThing</code> should be an independent type just floating around by itself. Two: if similar methods wind up being written for other classes, they will be returning different kinds of data (for good design reasons), and I don't want to clutter the namepace with a ton of similar-named structs that differ only slightly from each other.</p> <p>If we could upgrade our version of .Net, I would just return a <code>Tuple&lt;&gt;</code>, but that's not going to be an option for some time yet.</p> <p>[Edited to add: The small object does need to contain more than two fields, so <code>KeyValuePair&lt;K,V&gt;</code> won't quite cut it.]</p> <p>[Edited to add further: <code>IWidget</code> is implemented by only one class, <code>Widget</code>. I think it weird to have an interface for only one class, but this was done to satisfy an old coding policy that required the contract to always be in a separate assembly from the implementation. Said policy has now gone away, but we haven't the resources to refactor the entire application and remove all the unnecessary interfaces.]</p> <p>What's the best practice?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload