What is Generics in C#
Introduction
A notion called generic enables us to define classes and functions using placeholders. The provided category is substituted for these placeholders by the C# compiler at compilation time. Generating classes and methods with multiple uses involves the usage of generics. Additionally, using C# Generics, we can design a single class or Method that can be applied to several data types. We can reuse our code with the help of this.
Generics in C#
Generics are incorporated into C# 2.0. Generics give users the ability to define classes and methods that are independent of the data type. To put it another way, we may argue that Generics enable users to define classes by simply bracketing the data type of its members. Those angular brackets will be swapped for specified data types at compile times. The Generics apply to the following topics in C#:
- Interface
- Abstract class
- Class
- Method
- Static Method
- Property
- Event
- Delegates
Usage of Generics with Class and its Members in C#
Let's develop a generic class that includes a generic constructor, a generic member variable, generic property, and a generic function. The following code should be copied and pasted into a class file named GenericClass.cs.
Code
using System;
namespace GenericsDemo
{
//T specifies the Data Types of the class Members
class GenericClass<T>
{
private T GenericMemberVariable;
//Generic Constructor
//Constructor accepts one Parameter of Generic type, i.e., T
public GenericClass(T value)
{
GenericMemberVariable = value;
}
public T GenericMethod(T GenericParameter)
{
Console.WriteLine($"Parameter type: { typeof(T).ToString()}, Value: {GenericParameter}");
Console.WriteLine($"Return type: {typeof(T).ToString()}, Value: {GenericMemberVariable}");
return GenericMemberVariable;
}
public T GenericProperty { get; set; }
}
}
We constructed the class GenericClass using an argument in the example shown above. GenericClass is a generic class, as indicated by the angle brackets (), and its kind will be specified afterward. When creating an instance of the GenericClass class in the future, we must afterward define the T. The T data type is capable of being represented by primitive types such as int, float, long, etc., as well as reference types such as String, Object, Client, Worker, etc.
Thus, when creating a duplicate of the GenericClass class, one have to supply the type, and the compiler will assign that type to T. The data type in the following example is int. We call the GenericMethod function after creating an instance of the GenericClass. We were not required to define the T as an int when calling the class members because we did so when we created the instance.
using System;
namespace GenericsDemo
{
class Program
{
static void Main()
{
GenericClass<int> integerGenericClass = new GenericClass<int>(10);
int val = integerGenericClass.GenericMethod(200);
Console.WriteLine(val);
Console.ReadKey();
}
}
}
The collection classes that are part of System.Collections.Generic namespace employ the generics the most. Let's look at examples to learn more about employing generics in C# with classes, fields, and methods.
Generic Class in C#
The C# example below demonstrates how to create a generic class using type parameters (T) and angle brackets (>). In the example that follows, we've constructed a class with the type "T," as well as a variable and Method, both of which use the T argument. The T type was then supplied as a string when the instance was created. Therefore, during compilation, the string data type will be substituted for T wherever it appears in the GenericClass.
Code
using System;
namespace GenericsDemo
{
public class GenericClass<T>
{
public T Message;
public void GenericMethod(T Name, T Location)
{
Console.WriteLine($"Message: {Message}");
Console.WriteLine($"Name: {Name}");
Console.WriteLine($"Location: {Location}");
}
}
class Example
{
static void Main(string[] args)
{
Console.WriteLine("Generics Class Example in C#");
GenericClass<string> myGenericClass = new GenericClass<string>
{
Message = "Welcome"
};
myGenericClass.GenericMethod("Swami", "Hyderabad");
Console.ReadLine();
}
}
}
Output
![What is Generics in C#](https://static.tutorialandexample.com/csharp/what-is-generics-in-csharp1.png)
Generic Method in C#
Additionally, a method can be designated as generic in C#. i.e., to define the T> at the time the Method is created. The generic method can then be called while providing any kind of Parameter. Please see the example below, which demonstrates how to construct and invoke a generic method in C#, for a better understanding. The Generic Method is used for two generic arguments in the following example. As a result, while invoking the process, we need to provide the type for both T1 and T2.
Code
using System;
namespace GenericsDemo
{
public class SomeClass
{
public void GenericMethod<T1, T2>(T1 Param1, T2 Param2)
{
Console.WriteLine($"Parameter T1 type: {typeof(T1)}: Parameter T2 type: {typeof(T2)}");
Console.WriteLine($"Parameter 1: {Param1} : Parameter 2: {Param2}");
}
}
class Sample
{
static void Main(string[] args)
{
Console.WriteLine("Generic Method Example in C#");
SomeClass s = new SomeClass();
s.GenericMethod<int, int>(810,111 );
s.GenericMethod<double, string>(20.5, "Hiii");
s.GenericMethod<string, float>("Manideep", 40.5f);
Console.ReadLine();
}
}
}
Output
![What is Generics in C#](https://static.tutorialandexample.com/csharp/what-is-generics-in-csharp2.png)
Generic Field in C#
Generic fields of various generic kinds may be included in generic classes. The example that follows demonstrates the way to build and utilize a generic field in C# for greater comprehension. Here, we are defining two generic types, T1 and T2. We must specify the types for T1 and T2 when establishing the instance.
Code
using System;
namespace GenericsDemo
{
public class GenericClass<T1, T2>
{
public GenericClass(T1 Parameter1, T2 Parameter2)
{
Param1 = Parameter1;
Param2 = Parameter2;
}
public T1 Param1 { get; }
public T2 Param2 { get; }
}
class Sample
{
static void Main()
{
var obj1 = new GenericClass<int, string>(200, "Two Hundred");
Console.WriteLine($"{obj1.Param1} : {obj1.Param2}");
var obj2 = new GenericClass<string, string>("Hiii", "Welcome to C#.NET");
Console.WriteLine($"{obj2.Param1} : {obj2.Param2}");
var obj3 = new GenericClass<int, int>(400, 500);
Console.WriteLine($"{obj3.Param1} : {obj3.Param2}");
Console.ReadKey();
}
}
}
Output
![What is Generics in C#](https://static.tutorialandexample.com/csharp/what-is-generics-in-csharp3.png)
Advantages of Generics in C#
1. Code Reusability
It improves the code's reusability. For instance, you may develop a general method for adding two numbers. Both two integers and two floats can be added using this approach without modifying the original code.
2. Generics are Type-Safe
Generics offer type safety, particularly when used with collections. We must specify the kind of objects that will be supplied to a collection while utilizing generics. This aids the interpreter in making certain that the set of objects will only recognize object types that are defined in the definition. If we attempt to utilize another type of info from the one given in the description, we will encounter a compile-time error.
3. Better Performance
Generics provide better performance than non-Generics since they don't require as much boxing, unboxing, or typecasting of variables or objects.