C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

Definition And Use Of C# Generic Class

In this tutorial, we will explore the definition and use of generic classes in C#. A generic class is a class that has one or more type parameters. These type parameters act as placeholders for actual types, which are provided when you create an instance of the class. Generic classes allow you to write more flexible, reusable, and type-safe code by reducing the need for casting and code duplication.

  • Defining a Generic Class

To define a generic class, you include the type parameters inside angle brackets <T> after the class name, where T is a placeholder for the actual type you will use later.

Here's a simple example of a generic class called Box:

public class Box<T>
{
    public T Content { get; set; }

    public Box(T content)
    {
        Content = content;
    }
}

In this example, T is a type parameter that represents the type of the Content property.

  • Creating an Instance of a Generic Class

To create an instance of a generic class, you need to specify the actual type for the type parameter T. For example, you can create a Box to store an int or a string like this:

Box<int> intBox = new Box<int>(42);
Box<string> stringBox = new Box<string>("Hello, World!");
  • Accessing Properties and Methods in a Generic Class

When you create an instance of a generic class with a specific type, you can access its properties and methods just like with a non-generic class:

int intValue = intBox.Content; // 42
string stringValue = stringBox.Content; // "Hello, World!"
  • Adding More Type Parameters

You can define a generic class with more than one type parameter. Just separate them with commas inside the angle brackets:

public class Pair<T1, T2>
{
    public T1 First { get; set; }
    public T2 Second { get; set; }

    public Pair(T1 first, T2 second)
    {
        First = first;
        Second = second;
    }
}

In this example, the Pair class has two type parameters, T1 and T2. You can create instances of Pair with different combinations of types:

var intStringPair = new Pair<int, string>(1, "one");
var stringDoublePair = new Pair<string, double>("pi", 3.14159);
  • Generic Class with Methods

Generic classes can also have methods that depend on the type parameters. For example, you can add a PrintContent method to the Box class:

public class Box<T>
{
    // ...

    public void PrintContent()
    {
        Console.WriteLine($"Box content: {Content}");
    }
}

Now you can use the PrintContent method with different types:

intBox.PrintContent(); // Output: Box content: 42
stringBox.PrintContent(); // Output: Box content: Hello, World!

This tutorial demonstrates the basics of defining and using generic classes in C#. Generics are a powerful feature that enables you to create more flexible and reusable code, while preserving type safety.

  1. How to define a generic class in C#:

    • Description: A generic class is declared with one or more type parameters that represent the types it can work with.
    • Code:
      public class GenericClass<T>
      {
          public T Data { get; set; }
      
          public void DisplayData()
          {
              Console.WriteLine($"Data: {Data}");
          }
      }
      
  2. C# generic class example:

    • Description: An example of using a generic class with different data types.
    • Code:
      class Program
      {
          static void Main()
          {
              // Example of using a generic class
              GenericClass<int> intInstance = new GenericClass<int>();
              intInstance.Data = 42;
              intInstance.DisplayData();
      
              GenericClass<string> stringInstance = new GenericClass<string>();
              stringInstance.Data = "C# Generics";
              stringInstance.DisplayData();
          }
      }
      
  3. Generic class constraints in C#:

    • Description: Constraints restrict the types that can be used with a generic class, ensuring certain conditions are met.
    • Code:
      public class ConstraintClass<T> where T : IComparable
      {
          public T Data { get; set; }
      
          public void CompareTo(T other)
          {
              int result = Data.CompareTo(other);
              Console.WriteLine($"Comparison result: {result}");
          }
      }
      
  4. C# generic class with multiple type parameters:

    • Description: Generic classes can have more than one type parameter to handle scenarios requiring multiple data types.
    • Code:
      public class Pair<TFirst, TSecond>
      {
          public TFirst First { get; set; }
          public TSecond Second { get; set; }
      }
      
  5. C# generic class inheritance:

    • Description: A generic class can be inherited, and the derived class can specify the generic type parameter.
    • Code:
      public class DerivedClass<T> : GenericClass<T>
      {
          // Additional members or overrides can be added here
      }
      
  6. C# nested generic classes:

    • Description: A generic class can be nested within another class, providing encapsulation and modularity.
    • Code:
      public class OuterClass<T>
      {
          public class NestedClass<U>
          {
              public T OuterData { get; set; }
              public U NestedData { get; set; }
          }
      }
      
  7. Generic class and type inference in C#:

    • Description: Type inference allows the compiler to deduce the generic type based on the provided arguments, making code cleaner.
    • Code:
      public class InferenceClass<T>
      {
          public T GetData(T input)
          {
              return input;
          }
      }
      
      // Type inference in action
      InferenceClass<string> inferenceInstance = new InferenceClass<string>();
      string result = inferenceInstance.GetData("C# Type Inference");