Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat are alternatives to declaring data structure in functions?
    primarykey
    data
    text
    <p>Is there a good existing or upcoming alternative in C# to declaring data structures in methods? It's possible to use anonymous types, but there are difficulties with declaring them. Let's say I have a hypothetical class:</p> <pre><code>class ThingsManager { private void DoThings(IEnumerable&lt;Thing&gt; things) { var thingLocations = new Dictionary&lt;string, string&gt;(); foreach(var thing in things) { // some complicated logic and checks for current thing; // if current thing satisfies all conditions: var thingName = thing.Name; var thingLocation = location; // taken somewhere from upper lines thingLocations.Add(thingName, thingLocation); } // ... later foreach(var thingLocation in thingLocations) { // here I don't know what is the key and what does the value mean. // I could use Linq and anonymous types, but sometimes it is clearer // to use foreach if the logic is complicated } } } </code></pre> <p>Now, what I'd like to see:</p> <pre><code>class ThingsManager { private void DoThings(IEnumerable&lt;Thing&gt; things) { struct ThingLocations { string ThingName {get;set;} string Location {get;set;} } var thingLocations = new List&lt;ThingLocations&gt;(); foreach(var thing in things) { // some complicated logic and checks for current thing; // if current thing satisfies all conditions: var thingName = thing.Name; var thingLocation = location; // taken somewhere from upper lines thingLocations.Add(new ThingLocation(thingName, thingLocation)); } // ... later foreach(var thingLocation in thingLocations) { // now here I can use thingLocation.ThingName // or thingLocation.Location } } } </code></pre> <p>I could also declare the structure in the class, but it doesn't make sense to use it anywhere except in my function. It would be better if my function were the only place where I could use this data structure. I'm looking for a better way to handle such situations, or at least be able to declare anonymous types.</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.
    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