DEV Community

Cover image for Basics Of Generic Classes In C#
LetsUpdateSkills
LetsUpdateSkills

Posted on

Basics Of Generic Classes In C#

Introduction
I would like to share the basics of generics. Here first we will learn the problem statement and then resolve the problem using Generics.

Problem statement
First create a class as in the following code.

class CompareClass {  
    public bool Compare(string x, string y) {  
        if (x.Equals(y)) return true;  
        else return false;  
    }  
    public bool Compare(int x, int y) {  
        if (x.Equals(y)) return true;  
        else return false;  
    }  
}  
Enter fullscreen mode Exit fullscreen mode

Understanding the code
We created the CompareClass.

Here we created two compare methods, one for the string data type and the second for an int data type.

So the class contains overloaded compare functions.

Problem
So if we need to compare other datatypes like decimal, double and objects, then the code above would not work and we need to create another method to compare the proposed data type. We can solve this problem with generics.

Image description

Solution
Create a class as in the following code.

class CompareGenericClass < T > {  
    public bool Compare(T x, T y) {  
        if (x.Equals(y)) return true;  
        else return false;  
    }  
}  
Enter fullscreen mode Exit fullscreen mode

Understanding the code

  1. We created the class CompareGenericClass with the input parameter T so the class is CompareGenericClass

  2. Here T would be the datatype.

  3. If we want to compare strings then the following style would be used to create an object of the class,

Please click here to see complete tutorial

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs