How do I create and access a new instance of an Anonymous Class passed as a parameter in C#?

Anonymous types encapsulate a set of read-only properties. This explains

  1. Why Type.GetFields returns an empty array when called on your anonymous type: anonymous types do not have public fields.

  2. The public properties on an anonymous type are read-only and can not have their value set by a call to PropertyInfo.SetValue. If you call PropertyInfo.GetSetMethod on a property in an anonymous type, you will receive back null.

In fact, if you change

var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read()) {
    // No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
    T obj = (T)FormatterServices.GetUninitializedObject(typeof(T)); 
    foreach (PropertyDescriptor info in properties) {
        for (int i = 0; i < nwReader.FieldCount; i++) {
            if (info.Name == nwReader.GetName(i)) {
                // This loop runs fine but there is no change to obj!!
                info.SetValue(obj, nwReader[i]);
                break;
            }
        }
    }
    fdList.Add(obj);
}

to

PropertyInfo[] properties = sample.GetType().GetProperties();
while (nwReader.Read()) {
    // No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
    T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
    foreach (PropertyInfo info in properties) {
        for (int i = 0; i < nwReader.FieldCount; i++) {
            if (info.Name == nwReader.GetName(i)) {
                // This loop will throw an exception as PropertyInfo.GetSetMethod fails
                info.SetValue(obj, nwReader[i], null);
                break;
            }
        }
    }
    fdList.Add(obj);
}

you will receive an exception informing you that the property set method can not be found.

Now, to solve your problem, what you can do is use Activator.CreateInstance. I'm sorry that I'm too lazy to type out the code for you, but the following will demonstrate how to use it.

var car = new { Make = "Honda", Model = "Civic", Year = 2008 };
var anothercar = Activator.CreateInstance(car.GetType(), new object[] { "Ford", "Focus", 2005 });

So just run through a loop, as you've done, to fill up the object array that you need to pass to Activator.CreateInstance and then call Activator.CreateInstance when the loop is done. Property order is important here as two anonymous types are the same if and only if they have the same number of properties with the same type and same name in the same order.

For more, see the MSDN page on anonymous types.

Lastly, and this is really an aside and not germane to your question, but the following code

foreach (PropertyDescriptor info in properties) {
    for (int i = 0; i < nwReader.FieldCount; i++) {
        if (info.Name == nwReader.GetName(i)) {
            // This loop runs fine but there is no change to obj!!
            info.SetValue(obj, nwReader[i]);
            break;
        }
    }
}

could be simplified by

foreach (PropertyDescriptor info in properties) {
            info.SetValue(obj, nwReader[info.Name]);
}

I had the same problem, I resolved it by creating a new Linq.Expression that's going to do the real job and compiling it into a lambda: here's my code for example:

I want to transform that call:

var customers = query.ToList(r => new
            {
                Id = r.Get<int>("Id"),
                Name = r.Get<string>("Name"),
                Age = r.Get<int>("Age"),
                BirthDate = r.Get<DateTime?>("BirthDate"),
                Bio = r.Get<string>("Bio"),
                AccountBalance = r.Get<decimal?>("AccountBalance"),
            });

to that call:

var customers = query.ToList(() => new 
        { 
            Id = default(int),
            Name = default(string),
            Age = default(int), 
            BirthDate = default(DateTime?),
            Bio = default(string), 
            AccountBalance = default(decimal?)
        });

and do the DataReader.Get things from the new method, the first method is:

public List<T> ToList<T>(FluentSelectQuery query, Func<IDataReader, T> mapper)
    {
        return ToList<T>(mapper, query.ToString(), query.Parameters);
    }

I had to build an expression in the new method:

public List<T> ToList<T>(Expression<Func<T>> type, string sql, params object[] parameters)
        {
            var expression = (NewExpression)type.Body;
            var constructor = expression.Constructor;
            var members = expression.Members.ToList();

            var dataReaderParam = Expression.Parameter(typeof(IDataReader));
            var arguments = members.Select(member => 
                {
                    var memberName = Expression.Constant(member.Name);
                    return Expression.Call(typeof(Utilities), 
                                           "Get", 
                                           new Type[] { ((PropertyInfo)member).PropertyType },  
                                           dataReaderParam, memberName);
                }
            ).ToArray();

            var body = Expression.New(constructor, arguments);

            var mapper = Expression.Lambda<Func<IDataReader, T>>(body, dataReaderParam);

            return ToList<T>(mapper.Compile(), sql, parameters);
        }

Doing this that way, i can completely avoid the Activator.CreateInstance or the FormatterServices.GetUninitializedObject stuff, I bet it's a lot faster ;)