C# 3.0 - Using Anonymous Types

I had a friend who recently asked me on the ways using Anonymous Type in C# 3.0. Take note, this is just an example and to me it is like syntactic sugar. You can do the conventional way and it still works.

If you have a ComboBox within .NET Windows Forms and you like to programmatically configure the ComboBox with a list of values (Value & Member), normally people will do this:

   27             IList listOfAnimals = new ArrayList {

   28                 new Animal { Id = 10, Name = "Itik" },

   29                 new Animal { Id = 1, Name = "Ayam" }

   30             };

   31 

   32 

   33             comboBox1.DataSource = listOfAnimals;           

   34             comboBox1.ValueMember = "Id";

   35             comboBox1.DisplayMember = "Name";

   39     public class Animal

   40     {

   41         public int Id { get; set; }

   42         public string Name { get; set; }

   43     }

To me, it is a bit redundant to create an Animal class just for the purpose of programmatically setting the values to IList. Take note, tt will not read from the database and I am using ArrayList for this example. You can use other types of course. What if you have ComboBoxes that cater for Country, State, Cities, Phone Numbers, etc?

The other way that is most appealing will be:

   33     public class UltimateGenericComboBoxClass

   34     {

   35         public int Value { get; set; }

   36         public string Member { get; set; }

   37     } 

And you use it across all your programmatically ComboBoxes. 

As for me, I will recommend to consider using Anonymous types as below:

   22             IList listOfAnimals = new ArrayList {

   23                 new { Id = 10, Name = "Itik" },

   24                 new { Id = 1, Name = "Ayam" }

   25             };

   26 

   27             comboBox1.DataSource = listOfAnimals;           

   28             comboBox1.ValueMember = "Id";

   29             comboBox1.DisplayMember = "Name";

As the code above, within the ArrayList I will call new { Id = 10, Name = "Itik" }. I did not create any really redundant class for this. Let me know if you have a shorter way for this. Have fun. 

3 Comments

Comments have been disabled for this content.