nuno.filipesf
nuno.filipesf

Reputation: 775

Access Dictionary properties as Object

I have this classes:

public class Class1
{
    public Dictionary<string, Class2>  Items { get; set; }
}


public class Class2
{
    public string Code { get; set;}
    public string Name { get; set; }
}

And this

class Program
{
    static void Main(string[] args)
    {
        Class1 c = new Class1();
        c.Items = new Dictionary<string, Class2>();

        c.Items.Add("Item0001", new Class2() { Code = "0001", Name = "Item ABC" });
        c.Items.Add("Item0002", new Class2() { Code = "0002", Name = "Item XYZ" });
    }
}

What i want to know (i've already googled it but i can't find info about that) is if there is a way to access to the object like this, using the Intellisense or something similar.

c.Items.Item0001.Code

Upvotes: 1

Views: 405

Answers (1)

Kędrzu
Kędrzu

Reputation: 2425

Intellisense won't help you in this matter, because your dictionary items are defined in runtime, thus information about this is not available at compile time.

You can however use ExpandoObject and dynamic;

dynamic foo = new ExpandoObject();
foo.Item0001 = new Class1();
foo.Item0002 = new Class1();

var asDict = (IDictionary<string, object>)foo;
var item1 = asDict["Item0001"];

Upvotes: 6

Related Questions