Generics in C# with Practical Examples

Generics in C# with Practical Examples

Generics in C# are one of the most powerful features of the language, allowing developers to create flexible and reusable code. By using generics, you can create classes, methods, interfaces, and delega…


This content originally appeared on DEV Community and was authored by Azizul Arif

Generics in C# with Practical Examples

Generics in C# are one of the most powerful features of the language, allowing developers to create flexible and reusable code. By using generics, you can create classes, methods, interfaces, and delegates that work with any data type. This article will walk you through the concept of generics with practical examples, demonstrating how to use both single and multiple generic parameters.

What are Generics?

Generics allow you to define a class, method, or other data structures without committing to a specific data type. This means you can write code that is type-safe yet flexible enough to handle different data types, which reduces redundancy and enhances code reusability.

Single Generic Parameter Example

Let's start with a simple example: a User class that can store a user's registration number. However, instead of tying the class to a specific data type, we use a generic parameter, T, to make it flexible.

using System;

namespace GenericProperty
{
    // Single Generic
    public class User<T>
    {
        public T UserRegistrationNumber { get; set; }
    }
}

n the code above, the User class has a generic property UserRegistrationNumber of type T. This allows us to use the class with any data type.
Let's see it in action:

using System;

namespace GenericClassExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            User<int> user1 = new User<int>();
            user1.UserRegistrationNumber = 1234;
            Console.WriteLine(user1.UserRegistrationNumber);

            User<string> user2 = new User<string>();
            user2.UserRegistrationNumber = "LA1234";
            Console.WriteLine(user2.UserRegistrationNumber);

            Console.ReadKey();
        }
    }
}

In this example:

user1 is an instance of User, where T is an int.
user2 is an instance of User, where T is a string.
The output will be:

1234
LA1234

This demonstrates how the User class can handle different data types using a single generic parameter.

Multiple Generic Parameters Example
Next, let's explore using multiple generic parameters. We'll create a Survey class that can store both the registration status and age of a person. Since these two properties could be of different types, we'll use two generic parameters: RegStatus and Age.

using System;

namespace GenericProperty
{
    // Multiple Generics
    public class Survey<RegStatus, Age>
    {
        public RegStatus regStatus { get; set; }
        public Age age { get; set; }
    }
}

Now, let's see how to use the Survey class:
using System;

namespace GenericClassExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Survey<bool, int> person1 = new Survey<bool, int>();
            person1.regStatus = true;
            person1.age = 22;

            Survey<bool, string> person2 = new Survey<bool, string>();
            person2.regStatus = false;
            person2.age = "22-25";

            Console.WriteLine($"Person1 detail: Reg Status- {person1.regStatus}, Age- {person1.age}");
            Console.WriteLine($"Person2 detail: Reg Status- {person2.regStatus}, Age- {person2.age}");

            Console.ReadKey();
        }
    }
}

In this example:

person1 is an instance of Survey, where RegStatus is a bool and Age is an int.

person2 is an instance of Survey, where RegStatus is a bool and Age is a string.

The output will be:

Person1 detail: Reg Status- True, Age- 22
Person2 detail: Reg Status- False, Age- 22-25

This example highlights how multiple generics can be used to create a versatile and reusable class.


This content originally appeared on DEV Community and was authored by Azizul Arif


Print Share Comment Cite Upload Translate Updates
APA

Azizul Arif | Sciencx (2024-09-02T15:33:26+00:00) Generics in C# with Practical Examples. Retrieved from https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/

MLA
" » Generics in C# with Practical Examples." Azizul Arif | Sciencx - Monday September 2, 2024, https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/
HARVARD
Azizul Arif | Sciencx Monday September 2, 2024 » Generics in C# with Practical Examples., viewed ,<https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/>
VANCOUVER
Azizul Arif | Sciencx - » Generics in C# with Practical Examples. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/
CHICAGO
" » Generics in C# with Practical Examples." Azizul Arif | Sciencx - Accessed . https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/
IEEE
" » Generics in C# with Practical Examples." Azizul Arif | Sciencx [Online]. Available: https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/. [Accessed: ]
rf:citation
» Generics in C# with Practical Examples | Azizul Arif | Sciencx | https://www.scien.cx/2024/09/02/generics-in-c-with-practical-examples/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.