In this post, I am going to discuss about Generic Classes and bit more on this. Just for a smooth start,
“Generics were introduced in .NET 2.0, which provides us a way to create Classes/Methods/Types and many more without specifing the specific type of parameters. Parameters must be provided at the time of creating the instances. So we can say Generics are only a blueprint/templated version and actual type is defined at Runtime.”
So lets first create a simple Class say Point
public class Point<T> { }
Here as you can see, I have created a generic class Point, its coordinates X and Y can be of any type.
So in this post, I am going to mainly discuss, Constraint with generics.
Its very imperative to have a Generic Class, which can accept any type of parameter. But sometimes one might require that your generic Class can be instantiated with only specific types. Like say you want that a Generic can be instantiated with only say a Class Point Type or of its derived types. Is it possible ?
Yes this is possible.
And also, C# provides a very robust way to implement this feature. So using it, It can be very helpful at certain times to define a constraint over Generic.
So what are the ways to do this. We’ll first take few examples then. Later we will conclude .
So First, How can we define constraint with Generics. It is done using where clause.
We have two types of variable in C#. reference and Value..
No.. …
Now we have three types:
- Reference
- Value
- Nullable ( It is having feature of both types)
public class Point where T1 : struct { ... }
Public Class Queue: where T:Class { }
public class Point where T1 : class { ... }
Public class Point where T: struct, class { ... }
Public class Point where T: new() { ... }
public class Point where T1 : class, new() where T2 : IList { ... }
public class Point where T1 : int { ... }
But this is not possible. The constraint must be an interface, a non-sealed class or a type.
When you will compile will get an ERROR “A type used as a constraint must be an interface, a non-sealed class or a type”.
I was thinking to have this one also, but not there. But you might except it in the coming version of C#.
Hope you all must have liked this. Do share your feedback
Cheers,
Brij
Image may be NSFW.
Clik here to view.
Clik here to view.
