Generics and T in C#

Leave a comment

Generics in the .NET Framwork allow you to work with generic types without having to specify a data type until the class is instantiated.

Generics are useful, in that you may have a class that you don’t want to limit the functionality to a certain data type. For example, you may have a class that can compare 2 integers, or it could also compare 2 strings. Instead of creating 2 different classes and methods, you can create one generic class that handles both operations.

Let’s say we have a class like the one below, MyClass. We can define the class as generic by adding <>, for example <T> where T represents the generic type. The class contains one property, _t. We have one method, Display, which will return the value of _t:

        class MyClass<T>
        {
            private T _t;

            public MyClass(T t)
            {
                _t = t;
            }

            public string Display()
            {
                return String.Format("The value provided is: {0}. The type you provided is: {1}", _t, typeof(T));
            }
        }

Now, if we want to use this class, we would instantiate it like below:

            MyClass<int> i = new MyClass<int>(5);
            Console.WriteLine(i.Display());

            MyClass<string> s = new MyClass<string>("five");
            Console.WriteLine(s.Display());

This produces:

As can be seen, the first instance is an integer and the second is a string. Our generic class can handle both data types.

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *