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:
class ThingsManager
{
private void DoThings(IEnumerable<Thing> things)
{
var thingLocations = new Dictionary<string, string>();
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
}
}
}
Now, what I’d like to see:
class ThingsManager
{
private void DoThings(IEnumerable<Thing> things)
{
struct ThingLocations
{
string ThingName {get;set;}
string Location {get;set;}
}
var thingLocations = new List<ThingLocations>();
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
}
}
}
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.
Anonymous types would help with the naming aspect, but you would have to translate the input into your anonymous type and the type would remain internal to the method scope.
It is done using the
Selectextension method in order to project to an anonymous type.You can declare anonymous types without linq, but you will find it annoying trying to add those to lists / dictionaries:
I’m going on record to say that I wouldn’t take this approach, personally I’d either use anonymous types, a
Tuple<string, string>, or a custom type.Failing all of that, and if you don’t mind firing up the DLR, you could use an
ExpandoObject:This allows you to dynamically add properties as you need them by declaring them on the spot. You can then use these later because
ExpandoObjectprovides the plumbing to the DLR when the DLR asks for a member by name.