Retrieving Anonymous Object's Property in C#

95 Views Asked by At

I have the following code

using System;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        List<object> list = new List<object>();
        list.Add(new {
            Value = 0
        });
        //Console.WriteLine(list[0].Value);
    }
}

Is there a simple way to write the commented line of code without causing a compile time error? I know I could resort to using the dynamic keyword or implementing an extension method for the Object class that uses Reflection, but is there maybe another more acceptable way?

The goal is the avoid creating a class since its only purpose would be to store data. But at the same time still be able to retrieve the data later on in the program. This code will eventually end up in a web method which is why I want it to be dynamic / anonymous in the first place. All of the objects would end up having the same properties, as they would be storing values stored in tables, but the values are needed later for other calculations.

1

There are 1 best solutions below

4
On BEST ANSWER

Is there a simple way to write the commented line of code without causing a compile time error?

Not with the way you've declared the list. If your list will contain only objects of that anonymous type, you could use an array initializer and convert it to a List<{anonymous type}>:

var list = (new [] {
         new { Value = 0 }
     }).ToList();
Console.WriteLine(list[0].Value);

The nice thing is that you can add to the list easily, since anonymous types with the same properties are merged into one type by the compiler:

list.Add(new {Value = 1});

Per Servy's comment, a method to avoid an array creation would just be:

public static List<T> CreateList<T>(params T[] items)
{
     return new List<T>(items);
}

usage:

var list = CreateList(new { Value = 0 });