stuart-d2
5/26/2015 - 3:24 PM

List : Many Ways to Initialize

List : Many Ways to Initialize

/*
Multiple ways to initialize List  
	A. Collection Initailzer 
	B. Collection Initializer , var keyword (my favorite CSD)
	C. Collection with an Array as a Parameter
	D. Collection with Capacity in the Constructor
	E. Collection with the Add Method for each Element 
*/

	//using System;
	//using System.Collections.Generic;
	
	class Program {
	
	static void Main()
	{
	//A. Collection initializer,  
	List<string> weaponPartList = new List<string>()
	        {
	                "manipulator",
	                "shotgun arm",
	                "laser beam eyes"  
	        };
	
	//B.  ***Using a working variable, 
	//var keyword with the collection initializer.  
	//Quicker, less writing than doing  a traditional 
	//initializer pattern.
	// var <<WorkingName>> = new   
	var peacePartList = new List<string>() 
	        {
	                "reconciler",
	                "soother",
	                "medicine"
	        };
	
	
	//C. Use new array as parameter
	string[] legsArray = { "track", "wheels", "ball" };
	List<string> legsList = new List<string>(legsArray);
	
	
	
	//D. Use capacity in the contructor and assign
	//For some reason without these null assignments,
	// you will get a index out of range exception
	//ugly and bad, but it works, but dont do it.  
	List<string> listD = new List<string>(3);
	listD.Add(null); // Add empty references (BAD)
	listD.Add(null);
	listD.Add(null);  
	listD[0] = "fightBot"; 
	listD[1] = "flyBot";
	listD[2] = "bumBot";
	
	//E. Use Add for each element
	List<string> listE = new List<string>();  
	listE.Add("lasers");
	listE.Add("machine guns");
	listE.Add("missiles");
	
	        Console.WriteLine(weaponPartList.Count);
	        Console.WriteLine(peacePartList.Count);
	        Console.WriteLine(legsList.Count);
	        Console.WriteLine(listD.Count);
	        Console.WriteLine(listE.Count);
	}
	
	}