C# Generic constraints ( C# interview questions)

C# Generic constraints ( C# interview questions)


In this video will talk about what exactly are generic constraints and why do we need them Before I go ahead and I talk about generic constraints My suggestion is to go and see this video what are generics to understand the concepts of generics In this .NET fundamental section I have this video what are generics and generic collections In this video I will not be talking about the basics of generics Very focused on generics constraints In the fundamental section of the generic video that generics helps us to decouple the logic from the data type I have a data access layer class here and I have lot of business objects like customers, suppliers I have a customer class I have a supplier class My logic is data access layer inserts, updates and deletes object into the database and it will object from the database Attach this data access layer logic with the customer class Add a customer object Attach this data access layer logic with the supplier class and add the supplier into database Whole point of generic is to decouple the data type and the logic So you can have high reusability This attaching of data type with logic it looks a looks great idea This is a data access layer class. The data access layer class should able to add a supplier object it should be able to add a customer object or it should be able to add some kind of a business object It would be illogical to think about then I can attach integer data access layer now this is a illogical connection that I am able to attach integer data type with the data access layer so here I would like to put some kind of constraint With this logic you can attach only these kind of data types and that’s where generic constraints comes into a picture so to add a generic constraints to a generic You need put a where clause After the generic class you have to say where this any type should be of a typeclass It cannot be a integer, it cannot be a double, it cannot be a boolean It is throwing me a exception saying that you cannot attach this data type with this class over here If I attach a a customer type This project should actually compile Build started and build succeeded If I try to attach a integer data type This code should actually throw me a exception If I do a build here, already seeing red signs over here This will me through me a exception saying that it must be a reference type it cannot be a value type like a integer or a decimal A generic constraints helps you to put a constraint on your generic saying you can attach only these kind of data types to your logic This was a very simple demonstration of generic constraint I hope that you enjoyed this video thank you so much

One thought on “C# Generic constraints ( C# interview questions)

Leave a Reply

Leave a Reply

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