List vs ArrayList
Don’t use ArrayList
. Use List<T>
instead. ArrayList
comes from times when C# didn’t have generics and it’s not the same ArrayList
we have in Java.
DON’T
ArrayList array = new ArrayList();
array.Add(1);
array.Add("Pony"); // Later error at runtime if you try to operate with numbers.
do
List<int> list = [];
list.Add(1);
list.Add("Pony"); // Compilation error.
retrieve data
List<string> list = [ "yes", "no"];
var firstItem = list[0];
Tuples
Tuples help us manipulate data sets easily without having to define a new class with custom properties.
One of its benefits is that they can be used as method params and return types.
// simple tuple
(int, string) employee = (23, "Yohannes");
Console.WriteLine($"{employee.Item2} is {employee.Item1} years old");
// tuple with named parameters
(int Age, string Name) employee2 = (29, "Ramon");
Console.WriteLine($"{employee2.Name} is {employee2.Age} years old");
// nested tuples
var employees = ((23, "Yohannes"), (29, "Ramon"));
Console.WriteLine(employees.Item1); // (23, "Yohannes")
Console.WriteLine(employees.Item1.Item1); // 23
Tuples as function params
We can also use tuples as params for functions.
public void GetEmployee((string Name, int Age) employee)
{
Console.WriteLine($"{employee.Name} is {employee.Age} years old");
}
// call it as such
GetEmployee(("Yohannes", 23));
Tuples as the return type
public (string Name, int Age) GetEmployee()
{
return ("Yohannes", 23);
}
var emp = GetEmployee();
Console.WriteLine($"{emp.Name}, {emp.Age}");
Dictionary
Dictionaries are preferred over Hashtables, as they include type safety through generics.
Dictionary<string, string> dc = new Dictionary<string,string>();
dc.Add("txt", "hello world");
string value = string.Empty;
dc.TryGetValue("txt", out valor);
string value2 = dc["txt"];
Hashtable (use Dictionaries)
Hashtable table = new Hashtable();
table.Add("Alex", 2.34);
var valor = table["Alex"];
Stack
Colección LIFO (Last in, First Out). Pensar en una pila de platos. El último plato que ponemos es el primero en salir.
Stack pila = new Stack();
pila.Push(1);
var numero = pila.Pop();
Queue
Coleccion FIFO (First in, First Out). Pensar en una cola para un evento. El primero que llegó es el primero que entra.
Queue cola = new Queue();
cola.Enqueue(3);
var numero = cola.Dequeue();
Reference(s)
https://www.syncfusion.com/blogs/post/working-with-tuple-in-csharp