Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 120597
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T03:50:12+00:00 2026-05-11T03:50:12+00:00

I have created a function that takes a SQL command and produces output that

  • 0

I have created a function that takes a SQL command and produces output that can then be used to fill a List of class instances. The code works great. I’ve included a slightly simplified version without exception handling here just for reference – skip this code if you want to jump right the problem. If you have suggestions here, though, I’m all ears.

    public List<T> ReturnList<T>() where T : new()     {         List<T> fdList = new List<T>();         myCommand.CommandText = QueryString;         SqlDataReader nwReader = myCommand.ExecuteReader();         Type objectType = typeof (T);         FieldInfo[] typeFields = objectType.GetFields();         while (nwReader.Read())         {             T obj = new T();             foreach (FieldInfo info in typeFields)             {                 for (int i = 0; i < nwReader.FieldCount; i++)                 {                     if (info.Name == nwReader.GetName(i))                     {                         info.SetValue(obj, nwReader[i]);                         break;                     }                 }             }             fdList.Add(obj);         }         nwReader.Close();         return fdList;     } 

As I say, this works just fine. However, I’d like to be able to call a similar function with an anonymous class for obvious reasons.

Question #1: it appears that I must construct an anonymous class instance in my call to my anonymous version of this function – is this right? An example call is:

.ReturnList(new { ClientID = 1, FirstName = '', LastName = '', Birthdate = DateTime.Today }); 

Question #2: the anonymous version of my ReturnList function is below. Can anyone tell me why the call to info.SetValue simply does nothing? It doesn’t return an error or anything but neither does it change the value of the target field.

    public List<T> ReturnList<T>(T sample)      {         List<T> fdList = new List<T>();         myCommand.CommandText = QueryString;         SqlDataReader nwReader = myCommand.ExecuteReader();         // Cannot use FieldInfo[] on the type - it finds no fields.         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);         }         nwReader.Close();         return fdList;     } 

Any ideas?

Note: when I tried to use the FieldInfo array as I did in the function above, the typeFields array had zero elements (even though the objectType shows the field names – strange). Thus, I use TypeDescriptor.GetProperties instead.

Any other tips and guidance on the use of reflection or anonymous classes are appropriate here – I’m relatively new to this specific nook of the C# language.

UPDATE: I have to thank Jason for the key to solving this. Below is the revised code that will create a list of anonymous class instances, filling the fields of each instance from a query.

   public List<T> ReturnList<T>(T sample)    {        List<T> fdList = new List<T>();        myCommand.CommandText = QueryString;        SqlDataReader nwReader = myCommand.ExecuteReader();        var properties = TypeDescriptor.GetProperties(sample);        while (nwReader.Read())        {            int objIdx = 0;            object[] objArray = new object[properties.Count];            foreach (PropertyDescriptor info in properties)                 objArray[objIdx++] = nwReader[info.Name];            fdList.Add((T)Activator.CreateInstance(sample.GetType(), objArray));        }        nwReader.Close();        return fdList;    } 

Note that the query has been constructed and the parameters initialized in previous calls to this object’s methods. The original code had an inner/outer loop combination so that the user could have fields in their anonymous class that didn’t match a field. However, in order to simplify the design, I’ve decided not to permit this and have instead adopted the db field access recommended by Jason. Also, thanks to Dave Markle as well for helping me understand more about the tradeoffs in using Activator.CreateObject() versus GenUninitializedObject.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T03:50:12+00:00Added an answer on May 11, 2026 at 3:50 am

    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]); } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 165k
  • Answers 165k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer There are a couple of variants of a rename command,… May 12, 2026 at 12:33 pm
  • Editorial Team
    Editorial Team added an answer There is currently no way to build CLS-compliant assemblies from… May 12, 2026 at 12:33 pm
  • Editorial Team
    Editorial Team added an answer You might want to look at Google Protocol Buffers or… May 12, 2026 at 12:33 pm

Related Questions

Consider a SQL Server 2005 database with a bunch of data on a lot
I'm writing some DB routines and I'm using prepared statements. My environment is PDO
I have been tasked with creating a reusable process for our Finance Dept to
I am having a problem determining how c# and LINQ solve the common problem

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.