0

I have a small program below

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var obj = new {
            date = "Now",
            arr = animals
        };
        var obj2 = new {
            date = "later",
            arr = animals
        };
        var obj3 = new {
            date = "Never",
            arr = animals
        };
        
        var getVal = obj.date;
        Object [] x = {obj, obj2, obj3};
         Dictionary<string, Object []> myDict;
        myDict = new Dictionary<string, Object []>()
        {
            {"length", x},
          
        };
        
        var getVal2 = myDict["length"][1];
        //  var getVal2 = myDict["length"][1].date;  error no method date
        
        Console.WriteLine(getVal);
        Console.WriteLine(getVal2);
    }
}

How would I use getVal2 to get a date attribute from my object array. Accessing it outside the dictionary works fine from the variable: getVal and gives back the string "Now". How do I go about it for getVal2? Thanks

Megatron213
  • 81
  • 1
  • 12
  • 1
    The values within your dictionary are just `object[]`, which don´t have any `date`-property. You should definitly start to use named classes. Not only do they make your code far easier to understand, they also give you the opportunity to strongly type your objects and therefor to get compiler-support for everything you can do with those objects. – MakePeaceGreatAgain Jun 25 '21 at 14:55
  • Why do you even need a dictionary, when you only have a single value in it? – MakePeaceGreatAgain Jun 25 '21 at 14:56
  • Thanks @HimBromBeere Its an error I got from a bigger data set but exactly the same format. Any suggestion of how I would extract the value in this case? – Megatron213 Jun 25 '21 at 15:01

1 Answers1

1

When you call var getVal2 = myDict["length"][1]; you get type of object. To get your date property you need to cast object type into desirable type. Tricky here is that desirable type is anonymous but you can do it using a trick, by tricking the compiler into inferring the right type for you by creating additional method:

private static T Cast<T>(T _, object x)
{
    return (T)x;
}

Some people call this trick as "cast by example". The trick is that inside the assembly, the same anonymous type (same properties, same order) resolves to the same type, which makes the trick above work.

Example code:

public static void Main(string[] args)
{
    var anonymous = new { PropertyOne = 1, PropertyTwo = "2" };

    object myObject = anonymous;

    var result = Cast(anonymous, myObject);

    Console.WriteLine(result.PropertyOne);
    Console.WriteLine(result.PropertyTwo);
}

And in your case:

var getVal2 = Cast(obj, myDict["length"][1]).date;

Original post - Link

Qwertyluk
  • 363
  • 3
  • 14