C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

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#:

  1. Interface
  2. Abstract class
  3. Class
  4. Method
  5. Static Method
  6. Property
  7. Event
  8. 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#

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#

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#

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.