Generics

Generics in C#

Generics in C#

Generics in C# are a powerful feature that allows developers to define type-safe data structures and methods. By using Generics, you can write reusable and efficient code while avoiding runtime errors. This blog will dive deep into the concept of Generics, their syntax, and practical applications in C#.

What Are Generics?

Generics enable you to define classes, interfaces, and methods with a placeholder for the data type. This means you can work with any data type without compromising on type safety. Generics are particularly useful in scenarios where the exact data type is not known until runtime.

// Example of a Generic List List numbers = new List(); numbers.Add(10); numbers.Add(20); numbers.Add(30); foreach (int number in numbers) { Console.WriteLine(number); }

Why Use Generics?

  • Type Safety: Generics ensure type safety at compile time, preventing runtime type errors.
  • Performance: Generics reduce the overhead of boxing and unboxing when working with value types.
  • Code Reusability: You can create reusable classes and methods that work with any data type.
  • Improved Readability: Generics make your code cleaner and easier to understand by removing type-casting operations.

Common Examples of Generics

Some commonly used Generic classes in C# include:

  • List<T>: A dynamic array that can grow as needed.
  • Dictionary<TKey, TValue>: A collection of key-value pairs.
  • Queue<T>: A first-in, first-out (FIFO) data structure.
  • Stack<T>: A last-in, first-out (LIFO) data structure.

Defining a Generic Class

You can create your own Generic classes to work with multiple data types. Here's an example:

public class GenericClass { private T data; public void SetData(T value) { data = value; } public T GetData() { return data; } } // Usage GenericClass intInstance = new GenericClass(); intInstance.SetData(100); Console.WriteLine(intInstance.GetData()); GenericClass stringInstance = new GenericClass(); stringInstance.SetData("Hello Generics"); Console.WriteLine(stringInstance.GetData());

Defining a Generic Method

Generic methods allow you to create type-safe operations inside regular or Generic classes.

public void PrintArray(T[] array) { foreach (T item in array) { Console.WriteLine(item); } } // Usage int[] intArray = { 1, 2, 3, 4 }; PrintArray(intArray); string[] stringArray = { "A", "B", "C" }; PrintArray(stringArray);

Additional Examples

Here are some additional practical examples of Generics in action:

Generic Dictionary

Dictionary students = new Dictionary(); students.Add(1, "John"); students.Add(2, "Jane"); students.Add(3, "Jake"); foreach (var student in students) { Console.WriteLine($"ID: {student.Key}, Name: {student.Value}"); }

Generic Queue

Queue tasks = new Queue(); tasks.Enqueue("Task 1"); tasks.Enqueue("Task 2"); tasks.Enqueue("Task 3"); while (tasks.Count > 0) { Console.WriteLine(tasks.Dequeue()); }

Generic Stack

Stack prices = new Stack(); prices.Push(29.99); prices.Push(49.99); prices.Push(19.99); while (prices.Count > 0) { Console.WriteLine(prices.Pop()); }

Generic with Constraints

public class Shape { public virtual void Draw() => Console.WriteLine("Drawing a shape"); } public class Circle : Shape { public override void Draw() => Console.WriteLine("Drawing a circle"); } public class GenericDrawer where T : Shape, new() { public void DrawShape() { T shape = new T(); shape.Draw(); } } // Usage GenericDrawer drawer = new GenericDrawer(); drawer.DrawShape();

Constraints in Generics

In some cases, you might want to restrict the data types that can be used with your Generic class or method. This is where constraints come in.

  • where T : class: Restricts T to reference types.
  • where T : struct: Restricts T to value types.
  • where T : new(): Restricts T to types with a parameterless constructor.
  • where T : BaseClass: Restricts T to a specific base class or its derivatives.

Conclusion

Generics in C# provide a robust mechanism for type safety, code reusability, and performance optimization. By mastering Generics, you can write flexible and maintainable code, making your applications more robust and efficient.


This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication

Post a Comment

0 Comments