List as a Type in .Net Framework, Constructor Initializer and Object Initializer.

What is a List< T >


A list is a type in .Net framework that holds generic types. Therefore List could store multiple items just like an array. The < T > angled bracket  means the List is generic and could store any data type given to it. One of the unique characteristics of List < T > is it ability to identify the data type(either string, int, or a class we defined) been passed into it .


It should be noted that once a list type is specific that is only when new objects could be added to it. Generic is a topic that is more complex and beyond the level of this lesson, but you should have in mind that Generic refers to a class/method definition side of the equation. However, to make a class or method generic you can post-fix < T > it with the angled brackets.
To illustrate how List< T > works, Let us create a simple Car Class and pass in the Car Class as our List data type:

Public class Car
{
   public string Make { get; set;}
   public string Model { get; set;}
   public string Color { get; set;}
   public int Year { get; set;}
 } 

Now that we have the properties declared as Make, Model, Color, and Year, Now we need to assign value to these  properties  through the help of the class constructor and it must be declared inside the class scope:

public Car(string Make, string Model, string Color, int Year)
{
  this.Make = Make;
  this.Model = Model;
  this.Color = Color;
  this.Year = Year;
}

Understanding the Constructor


  • Public Car is declared just like a method but has no extra data type prefixing the Car since Car itself is a Class representing a type and it has an open and close parentheses invocation that takes in input parameters of  two different data types (string and int) just like any method we do. 
            Learn also: While() and do...while() loop in C#
  • A references is held to the Car Make through the help of  this keyword denoting the present position of where this Make belongs to (either its a Car Make or a Bus Make) in this case this class has this Make and the Make is assigned a value through the help of the constructor. However it could be simplify as  the C# compiler will know that it belongs to the Car Class as a property so an instance to references it  is not essential.  To simplify a  property being assigned a value from the constructor then they must not share same casing. I.e, Make = Make will means  an assignment being assigned to same variable which will not make the compiler happy by showing a squiggly green line beneath the assigned property(ies). In a nutshell to make the compiler happy we could re-frame this constructor like this: 

public Car(string make, string model, string color, int year)

{

   Make = make;

   Model = model;
   Color = color;
   Year = year;
}

Now either of these constructor could be use.Since we have assigned values to the the Class properties already we should be able to retrieve these values back from the properties they are assigned to, or narrower from where they are being stored. In this case  we need a  return helper method that we set in action to get this values out by return a string:
let us name this method FormatResultDetails( ): as it is we already know the name of the method through its functionality but now we need to implement it:

public string.FormatResultDetails()
{
   return string.Format("Make:{0}-Model:{1}-Color:{2}-Year: {3}<br/>",
   this.Make,
   this.Model,
   this.Color,
   this.Year.ToString());

}

Simplifying what this Code does


  • A public method  named FormatResultDetails( ) is declared and inside its code block we have a return string type  that return each item in the list to the caller. Note: The Object string reference its static method Format and format takes in a list of  string based on zero index upward (in this case 0 to 3 indexes). 
Now the Car class is completely structured and looks finally like this:

Public class Car
{
   public string Make { get; set;}
   public string Model { get; set;}
   public string Color { get; set;}
   public int Year { get; set;}

public Car(string make, string model, string color, int year)
{
   Make = make;
   Model = model;
   Color = color;
   Year = year;
}
public string.FormatResultDetails()
{
   return string.Format("Make:{0}-Model:{1}-Color:{2}-Year: {3}<br/>",
   this.Make,
   this.Model,
   this.Color,
   this.Year.ToString());
}
}

Now this Car class could be use as a type, such as: 
List<Car> cars  = new List<Car>( );

The question now is:


  • What is the purpose of this? 
  • Why do we need our Car class as a generic type?

One of the reasons is let say we want to create an application that have many instances of the object class. e.g:

Car  car1 = new Car ( );
Car  car2 = new Car( );
Car  Car3 = new  Car( );

In this case we are having 3  new cars in memory that would point to different values.
Mind you there are several ways we could populate each of this new Car with their own values, such as using:
  1. The Car constructor  declared  input parameter withing the invocation parentheses and assigned this parameter values to the properties that belong to the Car, such as the one we have seen above.
  2. We could at instantiation of a new object set it to a valid state, Of-course this is a good idea to set a new object to a valid state at instantiation.
How do we treat these two steps:

  1. The Car constructor: Instantiation of a new Car and populate its properties with using values within the invocation parentheses. we could set the using values of this assigned parameter like this  since we have designed there levels in the constructor method named Public Car( input parameters) from our Code above now we can populate the new object this way: 

Car  car1 = new Car ("Oldschool","Pegeout","White", 2018);
Car  car2 = new Car("Oldwagon", "Camry", "Black", 2016 );
Car  Car3 = new  Car("Oldstruct","Mercedez","Grey", 2018);

List<Car> cars = new List<Car>();


2. Instantiation of a new object and set it to a valid state:  i.e. Replacing Constructor with Object Initializer. 
Object Initializer makes it easy and straight to declare and assigned values to properties at a line of code during the instantiation of new object in this case new Car( ), therefore Object intializer is done right after the closing parentheses by opening two curly brackets and right inside the brackets we could declared our properties that shows an attributes common to the object's class  and assigned values to those properties. In this case we will practically remove the use of Constructor and instead of Constructor we will set the value to the properties directly at object instantiation. i.e.

Car  car1 = new Car (Make ="Oldschool", Model = "Pegeout", Color = "White", Year = 2018);
Car  car2 = new Car(Make = "Oldwagon", Model = "Camry", Color = "Black", Year = 2016);
Car  Car3 = new  Car(Make = "Oldstruct", Model = "Mercedez", Color = "Grey", Year = 2018);

List<Car> cars = new List<Car>();

Since we know the differences between Constructor initializer and Object Initializer: let say we want to  print out this List of cars , we could achieve this goal through the use of List <T> that stores generic type. Remember that our List< T> type must be specific before we could add objects to them. Now that we have the Car class representing our Type  and this Car class is having several instances that we created from it then we could add this to the List<Car> cars, if you have noticed you we see that under each initilizer that we created  we have already typed List< Car> cars = new List<Car>( ).  This means cars is ready to store each car coming from the initilizer, in this case we are going to deal with the constructor initilizer first. So now we will add 3 cars to the List<Car> through the help of Add( ) helper method available to the List<Car> instance. Right inside the Page_Load method code block you can type this:

Car  car1 = new Car ("Oldschool","Pegeout","White", 2018);
Car  car2 = new Car("Oldwagon", "Camry", "Black", 2016 );
Car  Car3 = new  Car("Oldstruct","Mercedez","Grey", 2018);
List<Car> cars = new List<Car>();

cars.Add(car1);
cars.Add(car2);
cars.Add(car3);

for(int i = 0; i < cars.Count; i++)
{
 result += cars[i].FormatResultDetails();
}

resultLabel.Test = result;


}
         
 Understanding the Code

We add the new Object to List with the help of the object instances in this case car1, car2, car3. Mind you there is what is called Unnamed Object that we could also add to List directly. Example is: 

List<Car> cars = new List<Car>();       
cars.Add( new Car {Make = "Oldschool", Model = "Pegeout", Color = "White",  Year = 2018 });
cars.Add(new Car { Make = "Oldvagon", Model = "Camry", Color = "Black", Year = 2016 });
cars.Add(new Car{ Make = "Oldstruct", Model = "Mercedez", Color = "Grey", Year = 2018 });

In this case we do not even need object's identifier, because the reference is being held by its position within the List and can be accessed as any list member, such as by iterating through it:

for (int i = 0 ; i < cars.Count; i++)
{
result+= cars[ i ]. FormatResultDetails();
}
resultLabel. Text = result;

  • We iterate through the cars and print it out with the help of the helper method we created and store each successive iteration to result by adding each result to new result the with the use of +=.
  • We return our result values to the resultLabel server control to push it out to screen.

Save and Run  to see the result:

https://www.maxybyte.com/2017/09/list-as-type-in-net-framework.html
List Example











2 comments:

  1. It’s very excellent information and more real facts to provided that post.Thank you for sharing this information. 700-651 exam questions

    ReplyDelete
    Replies
    1. Thank you for reading this post, and we are happy you find it helpful.

      Delete

Note: only a member of this blog may post a comment.