Generics Flashcards
With generics what can you do?
With generics, you can create classes and methods that are
independent of contained types.
What is generics?
Generics in C# allow you to define classes, methods, delegates, and interfaces with a placeholder for the type of data they store or use.
What are the benefits of generics?
Code reusability, type safety, and performance are benefits.
Value types are stored on the ______, reference types are stored on the ______.
stack, heap.
What is boxing?
The conversion from a value type to a reference type is known as boxing.
What is unboxing?
When a boxed value type can be converted to a value type.
With unboxing, the cast operator is required.
Is an array size static?
An array’s size is set at compile-time and is static
How is an ArrayList different from arrays?
- Items can be added and removed dynamically, and the ArrayList resizes itself.
- ArrayList belongs to System.Collections namespace.
- Add() method can be used to add items.
- ArrayList is not type-safe.
What are some benefits of generic lists compared to arrays and arraylists?
- List<T> stores elements of the specified type and it grows automatically.</T>
- List<T> can store multiple null and duplicate elements.</T>
- List<T> can be accessed using indexer, for loop or foreach statement.</T>
- LINQ can be used to query List<T> collection.</T>
- List<T> is ideal for storing and retrieving large number of elements.</T>
What’s the syntax to create a default constructor for an empty list?
List<int> myList = new List<int>();</int></int>
What’s the syntax to create a default constructor for a list with a capacity of 10?
List<int> myList = new List<int>(10);</int></int>
What does this code do?
Sets the myList capacity to 20.
What does this code do?
TrimExcess removes the unneeded capacity. However, because the relocation takes time, TrimExcess has no effect if the item count is more than 90 percent of capacity.
What does this code do?
Creates a list of int type and assigns it values and then prints “Total elements: “ and the count of all the elements.
Create the code for a foreach loop that iterates through the items in myList and prints the item
foreach (var item in myList)
Console.WriteLine(item);