Let's talk about constraints when it comes to C sharp generics.
So again Program.cs is clear.
And I've just created a new class called box.
We have used that class before because it's a great example for explaining C sharp generics.
Create that class if you want to follow along.
And let's use angle brackets and set the type to T.
Now what are constraints?
You know, we have already discovered that we can now with that generic class create a box of type integer
for example.
Right.
We can say let's call it box int.
That's fine right.
Or numeric box or whatever.
We can also put in our own data types.
Let's just create a class book here.
We don't have to create any properties.
It's just so that we can use this new data type.
So we can create a box with books inside.
So box book and then we call it book box.
There you go.
Right.
New box full of books.
All right.
So here we got a value type integer is a value type right.
And book is a class.
So we have an instance here and an object.
So it's a reference type.
But what if I only want our box our generic class to be available for classes for example.
So in easier words right.
I don't want our box to be able to get created with the integer type or with the float type, like any
value types, for example numeric values, right?
In that case, we can set up a constraint so we can limit this functionality.
This works if we say box of type T then where we use the keyword where, then where t is.
And then for example a class right.
So we set up a constraint.
Now we can only create an instance of our generic box where the generic type is a class.
So again if we would call that t key for example we would have to rename it here also.
Right.
Never forget to do that if you want to choose a different name than T.
However this is our constraint keyword where.
Then we use our type and then we use a colon and say has to be a class.
So if we now go to oh let me just save that.
If we now go to our program.cs, you can see that we are getting a compile time error, so that doesn't
work anymore.
If we hover above that, you can now see that the type int must be a reference type, right?
So for example a class right?
If we create an object of a class then it's stored inside of a variable.
And that variable references to the allocated memory in our computer to store that information.
Right.
So this is why it's called the reference type in order to use it as parameter t in the generic type
or method box t.
So basically this is how we can set up a very, very simple constraint so that you're not able to use
value types for your generic classes.
Alrighty.
So now you have learned how to set up a very simple constraint for a generic class so that you can improve
usability and type safety.
Let's move on to the next lesson.