Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Types

I have a Dictionary(TKey, TValue) like

Dictionary<int, ArrayList> Deduction_Employees = 
    new Dictionary<int, ArrayList>();

and later I add to that array list an anonymous type like this

var day_and_type = new {
    TheDay = myDay,
    EntranceOrExit = isEntranceDelay
};

Deduction_Employees[Employee_ID].Add(day_and_type);

Now how can I unbox that var and access those properties ??

like image 775
Mustafa Magdy Avatar asked Feb 19 '10 21:02

Mustafa Magdy


1 Answers

First, you aren't unboxing the type. Anonymous types are reference types, not structures.

Even though you can technically create instances of the same type outside of the method they were declared in (as per section 7.5.10.6 of the C# 3.0 Language Specification, which states:

Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type.

) you have no way of getting the name of the type, which you need in order to perform the cast from Object back to the type you created. You would have to resort to a cast-by-example solution which is inherently flawed.

Cast-by-example is flawed because from a design standpoint, every single place you want to access the type outside the function it is declared (and still inside the same module), you have to effectively declare the type all over again.

It's a duplication of effort that leads to sloppy design and implementation.

If you are using .NET 4.0, then you could place the object instance in a dynamic variable. However, the major drawback is the lack of compile-time verification of member access. You could easily misspell the name of the member, and then you have a run-time error instead of a compile-time error.

Ultimately, if you find the need to use an anonymous type outside the method it is declared in, then the only good solution is to create a concrete type and substitute the anonymous type for the concrete type.

like image 179
casperOne Avatar answered Sep 30 '22 02:09

casperOne