Robin Rodricks
Robin Rodricks

Reputation: 114126

Elegant way to save/load values into an array

I'm basically saving and loading values into an array to feed into a JSON library, and I'm just looking for a more elegant way to do this:

class properties to array

 return new object[] { path, pathDir, name };

array to class properties

c.path = values[0];
c.pathDir = values[1];
c.name = values[2];

Simple solutions that ideally do not require additional run time overheads such as Reflection are appreciated.

Can I do something like this?

  c.{path, pathDir, name} = values[0...2]

Edit: I'm specifically asking for arrays. I know about serialization and JSON and Protobuf and everything else everyone is suggesting.

Upvotes: 0

Views: 146

Answers (1)

DeeDub
DeeDub

Reputation: 1662

Would this not do the trick?

return  new {path= "/Some/Path", pathDir= "SiteRoot", name="MyPath"}

Edit:

 //Mock function to simulate creating 5 objects with 'CreateArrayOb' function
        public void CreatingObjects()
        {
            var lst = new List<object>();
            for (var x = 0; x < 5; x++)
            {
                lst.Add(CreateArrayOb(new string[] {"Path" + x, "Dir" + x, "Path" + x}));
            }
        }
        public object CreateArrayOb(object[] vals)
        {
            if (vals != null && vals.Any())
            {
                //Switch cases in the event that you would like to alter the object type returned
                //based on the number of parameters sent
                switch (vals.Count())
                {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        return new { path = vals.ElementAt(0), pathDir = vals.ElementAt(1), name = vals.ElementAt(2) };
                }

            }
            return null;
        }

Upvotes: 1

Related Questions