(C# Language) Practice Exercise on Anonymous Types

We have to store four properties of a record - student id of string type and marks in three subjects of Int32 type. Inside main create an array of 10 items. Use a for-loop to fill the array. Each item can be filled with random data. Then, use a select query on the array to project two fields only - Student ID and marks in the first subject. Print the queried data with a suitable loop. Use var keyword as far as possible.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Objectives of this Exercise

This exercise introduces you to

  1. Arrays in C#
  2. Random class of dotnet core
  3. Use of var keyword
  4. record class for holding data

Video Explanation (see it happen!)

Please watch the following youtube video:

The Solution

Create a C# .NET Core console project as usual. You can obtain the completed project from the downloads attached to this video. Now I will discuss the code.

Open the solution explorer and add a class called StudentMarks. We will change it to record class because we have to store init-once data. The syntax of a record with positional record makes it easier to define a data unit. The properties for id, marks1, marks2 and marks3 will be automatically created by the compiler because we have used the record keyword.


// obtain the source from the downloads  
// attached to this video 

// studentmarks.cs 

// positional parameters syntax used for  
// defining a record class 

record class StudentMarks 
          (String StuId, int Marks1, int Marks2, int Marks3);
  

Program.cs file

Again open the solution explorer so that we can complete the program.cs file. We shall use top level statements for writing our Main function.

We have used the var keyword to define an array of 10 records. The compiler can infer the correct data-type from the context.

After that we have an instance of the Random class so that we can generate random numbers.

A for loop is installed next. It runs over the entire length of the array.

The i-th element of the array gets a StudentMarks record. We do not have to write StudentMarks after the new keyword because it can be inferred by the compiler.

We have used Random dot Next to obtain a random number from 1 to 99.

Next we have to query the array. The easiest way is to use the Select extension method to obtain an enumerable collection of anonymous items. The Select function accepts a Func delegate that accepts one parameter and returns a data type.

We have used a statement lambda that accepts a StudentMarks item in identifier s and returns an anonymous type s => new { ID = s.StuId, Mks = s.Marks1 }.


using ConsoleApp1;

var data = new StudentMarks[10];

var rand = new Random();

for(int i = 0; i < data.Length; i++)
{
  // StudentMarks need not be 
  // written after the new keyword 
  // because the compiler can infer it 
  data[i] =  new (
                  $"ID_{i}", 
                  rand.Next(1, 100), 
                  rand.Next(1, 100), 
                  rand.Next(1, 100)
                  );
}

// function that returns anonymous for  
// a studentmarks object 
Func<StudentMarks, dynamic> fx 
                      = (s) => new { ID = s.StuId, Mks = s.Marks1 };

var items = data.Select(fx);

foreach(var m1 in items)
{
  Console.WriteLine(m1.ToString());
}

// -------------- additional notes (see video also) 

// shortcut was -  
// var items = data.Select (  
//      s => new { ID = s.StuId, Mks = s.Marks1 }); 

Next we use the Select extension method by passing the above delegate as its argument. The select method calls the above function on each item of the array and returns an anonymous object. So we get 10 anonymous objects in the items enumerable.

Notice that a short-cut is possible here. In fact, developers use this shortcut 99% of the time - .Select (s => new { ID = s.StuId, Mks = s.Marks1 }) The Func delegate has itself been passed as an anonymous here!

Finally, let us run the for-each loop on the enumerable items.

Lastly, we can run the project.


// one output 

{ ID = ID_0, Mks = 97 }
{ ID = ID_1, Mks = 46 }
{ ID = ID_2, Mks = 57 }
{ ID = ID_3, Mks = 90 }
{ ID = ID_4, Mks = 76 }
{ ID = ID_5, Mks = 2 }
{ ID = ID_6, Mks = 8 }
{ ID = ID_7, Mks = 3 }
{ ID = ID_8, Mks = 11 }
{ ID = ID_9, Mks = 45 }

We verify that our anonymous objects are printed as expected. Thankyou!


This Blog Post/Article "(C# Language) Practice Exercise on Anonymous Types" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.