C# / C# Collections and Generics

Creating Custom Generic Methods and Classes

In this tutorial, you'll learn how to create Custom Generic Methods and Classes in C#. These allow for the creation of flexible, reusable code that can work with any data type.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Introduces collections and generics to handle and manipulate data efficiently.

Introduction

Goal

In this tutorial, we will learn how to create Custom Generic Methods and Classes in C#. Generics are a powerful feature in C# that allow you to write a single class or method that works with a variety of types, without the need for casting or type checking.

Learning objectives

By the end of this tutorial, you will understand:
- The concept of Generics in C#
- How to create Generic Classes
- How to create Generic Methods

Prerequisites

To follow along with this tutorial, you should have:
- A basic understanding of C# and Object-Oriented Programming
- A development environment set up with C# (like Visual Studio or .NET Core)

Step-by-Step Guide

Generics are a feature of C# and .NET that allow you to define type-safe data structures, without committing to actual data types. This results in a high level of code reusability and cleaner code.

Generic Classes

A generic class can be defined using a type parameter in angle brackets after the class name. For example, the List<T> class in .NET is a generic class.

public class MyGenericClass<T>
{
    private T genericMemberVariable;

    public MyGenericClass(T value)
    {
        genericMemberVariable = value;
    }

    public T genericMethod(T genericParameter)
    {
        Console.WriteLine($"Parameter type: {typeof(T)}, value: {genericParameter}");
        Console.WriteLine($"Return type: {typeof(T)}, value: {genericMemberVariable}");

        return genericMemberVariable;
    }

    public T genericProperty { get; set; }
}

Generic Methods

Like generic classes, we can also have generic methods. A generic method is a method that is declared with type parameters, as shown below:

public void MyGenericMethod<T>(T parameter)
{
    Console.WriteLine($"Parameter type: {typeof(T)}, value: {parameter}");
}

Code Examples

Example 1: Generic Class

Below is an example of a generic class used to store a value of any type:

public class GenericClass<T>
{
    private T genericValue;

    public GenericClass(T value)
    {
        this.genericValue = value;
    }

    public T GetValue()
    {
        return this.genericValue;
    }
}

In this example, T is a placeholder for any type. You can create an object of GenericClass with any type:

var intClass = new GenericClass<int>(10);
Console.WriteLine(intClass.GetValue()); // Output: 10

var stringClass = new GenericClass<string>("Hello World");
Console.WriteLine(stringClass.GetValue()); // Output: Hello World

Example 2: Generic Method

Here is an example of a generic method that can accept parameters of any type:

public void DisplayValue<T>(T value)
{
    Console.WriteLine($"The value is: {value}");
}

This method can be called with any type of parameter:

DisplayValue<int>(100); // Output: The value is: 100
DisplayValue<string>("Hello World"); // Output: The value is: Hello World

Summary

In this tutorial, we have learned:
- What are Generics in C# and why to use them
- How to create Generic Classes and Methods

To further your understanding of Generics, you can:
- Learn about constraints in Generics
- Understand the difference between Covariance and Contravariance in Generics

Practice Exercises

  1. Create a generic class Pair that takes two parameters of any type and has a method to display both.
  2. Create a generic method that takes an array of any type and a value, and checks if the value exists in the array.

Solutions

  1. Generic class Pair:
public class Pair<T1, T2>
{
    private T1 firstValue;
    private T2 secondValue;

    public Pair(T1 first, T2 second)
    {
        this.firstValue = first;
        this.secondValue = second;
    }

    public void Display()
    {
        Console.WriteLine($"First: {firstValue}, Second: {secondValue}");
    }
}
  1. Generic method to check value in array:
public bool ContainsValue<T>(T[] array, T value)
{
    return array.Contains(value);
}

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help