Reusability in C#:
C# lets you reuse code in two major ways:
- Inheritance
- Generics
Let’s look at each:
1. Inheritance:
- Inheritance is an object-oriented concept.
- You write a base class and then extend it to create more specific classes.
- Example:
class Animal
{
public void Eat() { Console.WriteLine("Eating..."); }
}
class Dog : Animal
{
public void Bark() { Console.WriteLine("Barking..."); }
}
// Reusing code via inheritance
Dog d = new Dog();
d.Eat(); // From Animal
d.Bark(); // From Dog
✅ Pros: Useful when classes share common behavior.
❌ Cons: Less flexible when working with types (like
int
, string
, etc.)2. Generics:
- Generics allow you to write code using placeholder types.
- Instead of writing multiple versions of the same class or method for different types (e.g.,
int
,string
), you write one generic version. - Example:
class Box<T>
{
public T Value;
}
Box<int> intBox = new Box<int> { Value = 123 };
Box<string> strBox = new Box<string> { Value = "Hello" };
✅ Why Generics are Better in Some Cases?
1. Type Safety:
- Generics know the type at compile-time.
- You get intellisense and compile-time errors if you use the wrong type.
Box<int> b = new Box<int>();
b.Value = "Hello"; // ❌ Compile-time error
2. No Boxing/Unboxing:
- Boxing happens when a value type (like
int
) is converted to an object (reference type). - Generics avoid this, so they’re more efficient.
object x = 5; // boxing
int y = (int)x; // unboxing
- If you use
List<object>
, you’d box every value type. - With
List<int>
, there’s no boxing.
๐ง Imagine:
You are building a program to manage storage boxes.
Each box can store only one item, but it could be an item of any type — a book, a toy, a shirt, etc.
❌ Without Generics:
You might create different classes for each type:
class BookBox
{
public Book Item;
}
{
public Book Item;
}
class ToyBox
{
public Toy Item;
}
That's a lot of repetitive code and not scalable!
✅ With Generics:
Use one generic class for all types of boxes:
class StorageBox<T>
{
public T Item { get; set; }
}
Now you can create boxes for any type:
StorageBox<string> bookBox = new StorageBox<string>();
bookBox.Item = "C# Programming Book";
StorageBox<int> numberBox = new StorageBox<int>();
numberBox.Item = 123;
StorageBox<DateTime> dateBox = new StorageBox<DateTime>();
dateBox.Item = DateTime.Now;
๐ Benefits:
-
✔ Type-safe: You can't accidentally put a
DateTime
in aStorageBox<string>
. -
✔ Reusable: One class handles all types.
-
✔ Clean code: No code duplication.
๐งพ Real Code Example:
using System;
class StorageBox<T>
{
public T Item { get; set; }
}
class Program
{
static void Main()
{
var fruitBox = new StorageBox<string> { Item = "Apple" };
var numberBox = new StorageBox<int> { Item = 42 };
Console.WriteLine($"Fruit: {fruitBox.Item}");
Console.WriteLine($"Number: {numberBox.Item}");
}
}
Output:
Fruit: Apple
Number: 42
Comments
Post a Comment