When we write code like the one given below (in the console Main), Are we, in fact, instantiating the employee class? The employee class contains get and set for serial no, name, and a List for job title and constructor as well.
List<Employee> employee = new List<Employee>();
employee.Add(new Employee(1,"Thomas Alva Edison",new string[]{"Inventor"}));
My question is it like the basic instantiation as below.
Employee e1=new Employee(1,"Thomas Alva Edison",new string[]{"Inventor"}))
Code1 :
employees.Add(new Employee(1,"Thomas Alva Edison",new string[]{"Inventor"}));
We instantiate employee, do not save reference to it but add it to collection.
Code2 :
Employee e1 = new Employee(1,"Thomas Alva Edison",new string[]{"Inventor"});
We instantiate employee the same way but store reference to it in e1
variable.
With code2 you can still add it to collection via reference :
employees.Add(e1);
You can also access object inside your list by index or using LINQ :
var e = employees[0];
var e = employees.First();
It's also possible to fill collection with values using collection initializer :
List<Employee> employees = new List<Employee>()
{
new Employee(1,"Thomas Alva Edison",new string[]{"Inventor"})),
new Employee(2,"Kazem Zooo Benson",new string[]{"Inventor"})),
new Employee(3,"Mike Oslo Jameson",new string[]{"Inventor"}))
};
Sometimes it's more convenient to use Dictionary<TKey, TValue>
collection rather then List<T>
.
Let's assume that we are working with List<Employee>
from last example and we want to get only employee with first name "Mike".
With List<T>
we have to use LINQ
or foreach
to iterate the entire collection to find what we are looking for :
Employee mike = employees.First(e => e.Name.StartsWith("Mike"));
So it's kind of cumbersome. We can use dictionary to store names as a keys :
Dictionary<string, Employee> employees = new Dictionary<string, Employee>()
{
{"Thomas", new Employee(1,"Thomas Alva Edison",new string[]{"Inventor"})},
{"Kazem", new Employee(2,"Kazem Zooo Benson",new string[]{"Inventor"})},
{"Mike", new Employee(3,"Mike Oslo Jameson",new string[]{"Inventor"})}
};
In this scenario if we want to get Person named Mike we only need to access the key of our dictionary:
Employee mike = employees["Mike"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With