Generics in C# | Learn Generic Classes and Methods
C Generics Tutorial ACTE

Generics in C# Tutorial | Learn Generic Classes and Methods

Last updated on 28th Jan 2022, Blog, Tutorials

About author

Jagan Mohan (Senior C# Developer )

Jagan Mohan is a Senior Senior C# Developer and has extensive knowledge in the following areas: WPF, XML, REST, Agile, V Model, C#, SQL Server, Web API, ASP, and.NET.

(5.0) | 17891 Ratings 1694
    • Introduction of C# Generics
    • Reason to utilize Generics of C#
    • To create objects of generic class, following syntax is used
    • A Generic strategy with different boundaries
    • Launching Generic Class
    • Conventional Class Characteristics
    • Conventional Fields
    • Conventional Methods
    • Boxing and Unboxing for Generics C#
    • What is a conventional strategy C#?
    • C# Generics Overview
    • Elements of Generics
    • Collections namespace
    • Benefits
    • Advantages
    • Pre-Requisites
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction of C# Generics:

      Nonexclusive means the overall structure is not explicit. In C#, nonexclusive means not explicit to a specific information type. C# permits you to characterize nonexclusive classes, interfaces, conceptual classes, fields, strategies, static techniques, properties, occasions, representatives, and administrators utilizing the sort boundary and without the particular information type. A sort boundary is a placeholder for a specific kind determined while making an occurrence of the nonexclusive sort. A nonexclusive kind is announced by indicating a sort boundary in a point section after a kind name, for example, TypeName where T is a sort boundary.


       C# Generics
      C# Generics

      Generics in C# is its most remarkable component. It permits you to characterize the sort of safe information structures. This out-turn is an exceptional exhibition lift and high-grade code, since it assists with reusing information handling calculations without duplicating type-explicit code. Generics are like formats in C++ yet are different in execution and capacities. Generics presents the idea of type boundaries, due to which it is feasible to make techniques and classes that concedes the outlining of information type until the class or strategy is proclaimed and is started up by customer code. Conventional sorts perform better compared to typical framework types since they decrease the requirement for boxing, unpacking, and type projecting the factors or articles.


      Reason to utilize Generics of C#:

      There are two motivations to involve generics as in the accompanying:

      1. Performance: Collections that store the articles utilize boxing and unpacking on information types. An assortment can decrease the presentation. By utilizing generics, it assists with working on the exhibition and type security.


      2. Type Safety: there is no solid sort data at gather time concerning what is put away in the assortment.

      • When to utilize Generics, Whenever you utilize different #ff0000 information types, you want to make a nonexclusive kind.
      • It is more straightforward to compose code once and reuse it for quite a long time.
      • On the off chance that you are dealing with a worthy kind, for that boxing and unpacking activity will happen, Generics will kill the boxing and unpacking tasks.

     Reason to utilize Generics of C#
    Reason to utilize Generics of C#

      To create objects of generic class, following syntax is used:

      BaseType obj = new BaseType ()

        Generic class
        Description
        Collection<'T'> The basis for a generic collection Comparer compares two generic objects for equality
        Dictionary<'TKey, Tvalue'> A generic collection of name/value pairs
        List<'T'> A dynamically resizable list of Items
        Queue<'T'> A generic implementation of a first-in, first-out (FIFO) list
        Stack<'T'> A generic implementation of a last-in, first-out (LIFO) list

    Course Curriculum

    Learn C and C Plus Plus Certification Training Course to Build Your Skills

    Weekday / Weekend BatchesSee Batch Details

      A Generic strategy with different boundaries:

      Just as a technique can take one contention, generics can take different boundaries. One contention can be passed as a recognizable sort and the other as a conventional kind, as displayed underneath:

      Model:

      • // C# program to show different
      • // type boundaries in Generics
      • utilizing System;
      • public class GFG {
      • // Generics technique
      • public void Display<'TypeOfValue'>(string msg, TypeOfValue esteem)
      • {
      • Console.WriteLine(“{0}:{1}”, msg, esteem);
      • }
      • }

      Launching Generic Class:

      You can make an occurrence of conventional classes by indicating a genuine kind in point sections. The accompanying makes an occasion of the conventional class DataStore. DataStore<'string'> store = new DataStore<'string'>();


      Conventional Class Characteristics:

    • A conventional class expands the reusability. The more sort boundaries mean more reusable it becomes. In any case, an excess of speculation makes code hard to comprehend and keep up with.
    • A conventional class can be a base class to other nonexclusive or non-nonexclusive classes or theoretical classes.
    • A nonexclusive class can be gotten from other conventional or non-conventional connection points, classes, or unique classes.

      Conventional Fields:

      A nonexclusive class can incorporate conventional fields. Be that as it may, it can’t be introduced.

      Model: Generic Field


      • class DataStore<'T'>
      • {
      • public T information;
      • }

      Conventional Methods:

      A strategy announced with the kind boundaries for its return type or boundaries is known as a conventional technique.

      Model: Generic Methods

      • class DataStore<'T'>
      • {
      • private T[] _data = new T[10];
      • public void AddOrUpdate(int record, T thing)
      • {
      • if(index >= 0 && list < 10)
      • _data[index] = thing;
      • }
      • public T GetData(int list)
      • {
      • if(index >= 0 && list < 10)
      • return _data[index];
      • else
      • return default(T);
      • }
      • }

      Boxing and Unboxing for Generics C#:

      Net characterizes two significant classes of information type named esteem type and reference type to address a variable. This is the place where boxing and unpacking are required. Boxing is an instrument to unequivocally change over a worth kind to a reference type by putting away the variable into System. Object; when you box the worth the CLR distributes another item into the stack and duplicates the worth sort’s worth into that occurrence.


      There are a series of tasks performed by .NET CLR, for example, initial an article is distributed in the oversaw load, then, at that point, in confining the worth is changed to the memory area, and during unpacking the worth is put away on the store and should be moved back to the stack. So the Boxing and Unboxing process has a huge significance in Generics according to the exhibition perspective since this interaction is more asset concentrated rather than utilizing Generics.


    Course Curriculum

    Get JOB Oriented C and C Plus Plus Training for Beginners By MNC Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

      What is a conventional strategy C#?

      A conventional technique is a strategy that is pronounced with type boundaries, as follows: C# Copy. static void Swap<'T'>(ref T LHS, ref T RHS) { T temp; temp = LHS; LHS = RHS; RHS = temp; } The accompanying code model shows one method for calling the strategy by utilizing int for the kind contention: C# Copy.


      C# Generics Overview:

      Coming up next are the significant properties of generics in the c# programming language.

    • In c#, generics are addressed by utilizing point section.
    • To characterize a class or technique as conventional, we want to involve a sort boundary as a placeholder with point sections.
    • The compiler will supplant every one of the placeholders with the predefined type at an aggregate time.
    • In c#, generics are valuable for further developing the code reusability, type security, and execution contrasted and non-nonexclusive sorts like ArrayList.
    • In c#, you can utilize generics with interfaces, classes, strategies, properties, agents, occasions, and administrators.

      Elements of Generics:

      Generics is a method that enhances your projects in the accompanying ways −

    • It assists you with augmenting code reuse, type wellbeing, and execution.
    • You can make nonexclusive assortment classes. The .NET Framework class library contains a few new nonexclusive assortment classes in the System.Collections.Generic namespace.

      Collections namespace:

    • You can make your nonexclusive points of interaction, classes, strategies, occasions, and delegates.
    • You might make nonexclusive classes compelled to empower admittance to strategies on specific information types.
    • You might get data on the kinds utilized in a conventional information type at showtime to a method for reflection.

      Benefits:

      Coming up next are the advantages of generics:

    • There is no requirement for projecting for getting to the components of the information.
    • Code isn’t copied for a considerable length of time of information.
    • Generics can hold the information with a similar sort and we can conclude what kind of information that the assortment holds.
    • You can make your nonexclusive point of interaction, classes, strategy, occasions, and agent.

      Advantages:

    • Reusability: You can involve a solitary nonexclusive sort definition for quite a long time in a similar code with practically no adjustments. For instance, you can make a nonexclusive technique to add two numbers. This strategy can be utilized to add two whole numbers just as two floats with next to no alteration in the code.
    • Type Safety: Generic information types give better sort wellbeing, particularly on account of assortments. While utilizing generics you want to characterize the sort of objects to be passed to an assortment. This assists the compiler with guaranteeing that main those article types that are characterized in the definition can be passed to the assortment.
    • Execution: Generic sorts give better execution when contrasted with typical framework types since they diminish the requirement for boxing, unpacking, and pigeonholing of factors or articles.

      Pre-Requisites:

      It’s one thing to feel certain about your groups’ mechanical capacities. It’s one more to realize they have the stuff. Presently there’s a simpler way for them to demonstrate their capability and it can save your association critical time and exertion. With the O’Reilly certificate insight, your groups get immediate ways to the authority prep materials in addition to rehearse tests for the most sought-after confirmations in the business.


      Conclusion:

      Generics address a significant however somewhat late option to the C# language (first included C# 2005). This valuable expansion reflects the same instrument in Java. The explanation that generics are fascinating isn’t simply because of the gigantic code investment funds that can be accomplished cautious utilization of generics likewise takes into consideration more nonexclusive code! All in all, you don’t need to continue to rehash an already solved problem. An illustration of this standard is nonexclusive assortments. The last sort is made at runtime rather than at arranged time. Conventional classes additionally give the typical highlights of legacy, interface execution, etc. You just supplement the necessary sort at runtime, and the class occasion is accurately bound.


      C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      The System.Collections.Generics namespace remembers a wide scope of helpful sorts for expansion to List. Every one of these kinds genuinely deserves study. List occasions can likewise be arranged and looked at, without the need to make unique strategies. At the end of the day, the difficult work of composing the sort and search code is as of now accomplished for you, so you can continue ahead with characterizing your application rationale. The List type additionally gives a set-up of helpful properties and strategies, for example, Count, which returns the number of components in the assortment.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free