C# Generics And Constraints

Recap

I recently wrote a post going over C# Generics and why we use them. One topic which I did not cover in that post was constraints. Basically, constraints are an additional type of enforcement on what types of parameters can be used in a class which implements generics. From my previous post, we understand that Generics in .NET allows us to add placeholders for types to our classes, fields, methods, and parameters.

For example, the following class shows a class which implements generics:

where keyword

Now, what if we wanted to further limit the types of placeholders that could be used in our class? This is where constraints come in. We use the where keyword in the following example when declaring our class signature.

Notice that it comes directly after declaring our class as using a generic type <T>. To further declare what type our class is we use the following where T: class.

You can also apply multiple constraints by declaring class GenericClass<T, U> where T: class where U: struct { ... code for class implementation ...}. T and U are merely the placeholder for your generic types.

Some limits to constraints and type parameters

You should note that there are some limits to what can be used for your constraints. I did pull these from MSDN so feel free to research additionally on your own.

Type Description
where T : struct The type argument must be a value type.
where T : class The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type.
where T : unmanaged The type argument must not be a reference type and must not contain any reference type members at any level of nesting.
where T : new() The type argument must have a public parameterless constructor.
where T : <base class name> The type argument must be or derive from the specified base class.
where T : <interface name> The type argument must be or implement the specified interface. The constraining interface can also be generic.

Anyhow, shorter post this week, but I hope you found it useful in addition to my previous post on generics and are able to put this to good use!

Next On FoC

Finding Your Niche as a Developer

Finding Your Niche as a Developer
JavaScript Code Nesting and Lexical Environments Explained
Previously On FoC

JavaScript Code Nesting and Lexical Environments Explained

JavaScript Code Nesting and Lexical Environments Explained