Type Safety with Generics

How generics prevent bugs

Posted by Rodrigo Castro on November 24, 2024

Generics keep your code type-safe, because C# checks that you use the right types.

🚫 Without Generics

Using object is flexible, but risky:

1
2
3
4
ArrayList items = new ArrayList();
items.Add("hello");
items.Add(123); // Oops different type!
string s = (string)items[1]; // Error at runtime!

✅ With Generics

With generics, C# checks types for you:

1
2
3
List<string> words = new List<string>();
words.Add("hello");
// words.Add(123); // Compile-time error!

🛡️ Why it Matters

  • Fewer runtime errors (bugs pop up before running the program).
  • Code is easier to read and maintain.

💡 Try It!

Create a List<int> and add numbers. Try to add a string… what happens?

1
2
3
List<int> numbers = new List<int>();
numbers.Add(1);
// numbers.Add("two"); // Compile error

Next: Exception handling!