C# Generics

C# Code Snippets Generics
Share:

About

In this code snippet, we will learn about generics in C#.

You can make generic classes, properties, methods, and parameters. If we make something generic this means it doesn’t have a type. Or better said the type is determined at compile time.

This can be very useful. For example, let’s say we have a method called display() that takes some text in as an input parameter and then writes that text to the console window. If we want to write out an int we first have to convert it into a string. But if we make the input parameter generic we don’t have to worry about converting to the correct data type. Also, method return types can be generic as well.

Generic classes can have constraints applied to them. This will limit the types that can be used.

Let’s see how to implement generics in the code example below.

Code:

using System;
namespace Generics
{
    class Program
    {
        static void Main(string[] args)
        {
            //Generic method.
            display<int>(10);
            display<double>(2.2);
            display<string>("Hello.");

            //Generic class with generic properties and methods.
            MyClass<int> mc1 = new MyClass<int>(10);
            mc1.displayMyProperty<int>();

            MyClass<string> mc2 = new MyClass<string>("Hello form MyClass.");
            mc2.displayMyProperty<string>();

            MyConstrainedClass<int> mcc = new MyConstrainedClass<int>();

            //This will throw an error at compile time as object is a reference type
            //and we made a constraint only allowing value types like int.
            //MyConstrainedClass<object> mcc = new MyConstrainedClass<object>(); 

            Console.ReadLine();
        }

        //Method with a generic input parameter. The "<T>" makes a method generic.
        public static void display<T>(T inputData)
        {
            Console.WriteLine(inputData);
        }
    }

    //Classes(and structs) can be generic too. The "<T>" makes a class generic.
    class MyClass<T>
    {
        //The "<T>" makes the property generic.
        public T MyProperty { get; set; }

        public MyClass(T inputData)
        {
            MyProperty = inputData;
        }

        //Method with a generic return type and a generic input parameter. The "<T>" makes a method generic.
        public static T aGenericMethod<T>(T inputData)
        {
            //This is a pointless method ... It just shows that a method can have a generic input parameter and return type.
            return inputData;
        }

        //Method with a generic input parameter. The "<T>" makes a method generic.
        public void displayMyProperty<T>()
        {
            //The "aGenericMethod" just passes the value of "MyProperty" through it... Again this is useless but it's just to show how generics work.
            Console.WriteLine(aGenericMethod(MyProperty));
        }
    }

    //Generic classes can also have constraints applied to them. This will limit the generic types that can be used.
    //See possible constraints here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
    class MyConstrainedClass<T> where T : struct //This will only allow value types to be used.
    {
        //The "<T>" makes the property generic.
        public T MyProperty { get; set; }
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger