Home › C# › Generics and T in C#
C# · Sep 1, 2016 · 2 MIN READ

Generics and T in C#

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.

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

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

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.