Generics
List Type Safety
List<T> stores a collection where every item has the same type.
List Type Safety
ListTypeSafety.cs
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int extra = ;
List<int> scores = new List<int>();
scores.Add(10);
scores.Add(extra);
int total = 0;
foreach (int score in scores)
{
total += score;
}
Console.WriteLine($"extra={extra}");
Console.WriteLine($"count={scores.Count}");
Console.WriteLine($"total={total}");
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int extra = ;
List<int> scores = new List<int>();
scores.Add(10);
scores.Add(extra);
int total = 0;
foreach (int score in scores)
{
total += score;
}
Console.WriteLine($"extra={extra}");
Console.WriteLine($"count={scores.Count}");
Console.WriteLine($"total={total}");
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int extra = ;
List<int> scores = new List<int>();
scores.Add(10);
scores.Add(extra);
int total = 0;
foreach (int score in scores)
{
total += score;
}
Console.WriteLine($"extra={extra}");
Console.WriteLine($"count={scores.Count}");
Console.WriteLine($"total={total}");
}
}
type safety
Type safety catches mismatched values before a program runs.