SlideShare a Scribd company logo
ge⋅ner⋅ic –adjective  Also,  ge⋅ner⋅i⋅cal. 1. of, applicable to, or referring to all the members of a genus, class, group, or kind; general.
“ Generic", unrelated to the programming world, it simply means something that is not tied to any sort of brand name.  For example, if we purchase some generic dish soap, soap that has no brand name on it, we know that we are buying dish soap and expect it to help us clean our dishes. We can treat it as dish soap even though we don't really have any idea of its exact contents.
Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. You can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations
Generics are a new feature in version 2.0 of the common language runtime (CLR). Generics use the new keyword  Of By creating a generic class, you can create a collection that is type-safe at compile-time. Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot.
The most basic type of a collection is an array; however, arrays can be difficult to use, particularly when the number of items in the array varies and when the actual items in the array vary or move around.  To address these limitations, we have  Collections,  which are more or less friendly wrappers around arrays. More important, they enable us to interact with collections of types in a familiar way, just as we might interact with a collection of items in the real world.
The problem with collections in the first version of .NET is that in order for them to be strongly typed, the developer would have to write custom collections for each and every type, overriding or implementing methods (such as Add, Remove, Contains, etc.) and indexers on each one Life was also hard for the computer because in order to generalize collection types enough, it had to use the Framework base class, Object, in order to provide the needed flexibility. Value types had to put them into a special package known as a boxing in order to store them in the collection (because the collection was of the Object type, which is a reference type).
Any reference or value type that is added to an  ArrayList  is implicitly upcast to  Object . If the items are value types, they must be boxed when they are added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations decrease  performance ; the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collections
The other limitation is lack of  compile-time  type checking; because an  ArrayList  casts everything to  Object , there is no way at compile-time to prevent client code from doing something such as this:
Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The .NET Framework class library contains several new generic collection classes in the  System.Collections.Generic  namespace. These should be used whenever possible in place of classes such as  ArrayList  in the  System.Collections  namespace.
Can create custom own generic interfaces, classes, methods, events and delegates. Generic classes may be constrained to enable access to methods on particular data types. Information on the types used in a generic data type may be obtained at run-time by means of reflection.
What a "type" is in .NET   "Type" is simply short hand for "type of data" or "data type"; a type tells the computer how to store information (data) and what will be done with that information.    What Is meant by strongly typed? means that the computer has enough information-a clear blueprint-on how to deal with particular data 
What is Type Parameter A type parameter is the core of enabling generic functionality.  For types, it is kind of like a constructor parameter.  For methods, it's like other parameters except that it can often be inferred
What is Generic Type? A definition of a class, structure, interface, procedure, or delegate for which you supply at least one data type when you declare it. What is Generic method?   A generic method is any method that defines one or more type parameters, as in the DoSomething method It is important to note that generic methods do not have to be declared within generic types
Type Parameter In a generic type definition, a placeholder for a data type you supply when you declare the type. Type Argument A specific data type that replaces a type parameter when you declare a constructed type from a generic type.
Constraint A condition on a type parameter that restricts the type argument you can supply for it.  A constraint can require that the type argument must implement a particular interface, be or inherit from a particular class, have an accessible parameter less constructor, or be a reference type or a value type. You can combine these constraints, but you can specify at most one class.
What is Constructed Type? This means a type that is created (constructed) as a result of the usage of a generic type. A class, structure, interface, procedure, or delegate declared from a generic type by supplying type arguments for its type parameters. What are called Closed constructed types? At design-time we know the type that is being passed to it What are called open constructed types?
C# public class MySample<T> {        public void DoSometing<K,V>()        {} } VB .NET Public Class MySample(Of T)        Public Sub DoSomething(Of K, V)()        End Sub End Class
C# MySample<string> someSample; VB .NET someSample As MySample(Of String)
C#   public class MyExample<V>        {private MySample<V> someSample;} VB .NET      Public Class MyExample(Of V)        Private someSample As MySample(Of V)      End Class
What is Constrain in .NET Generics? That enable the creator of a generic to specify that only certain types may be passed in as type arguments to his generic.
C#        public class MyClass<T, K> {          public void DoSomething() {                    T temp = new T();                   Debug.Assert(temp.Contains(“test”)); }} VB .NET        Public Class MyClass(Of T, K)              Public Sub DoSomething()                    Dim temp As T = New T()                   Debug.Assert(temp.Contains(“test”))              End Sub        End Class
C#        public class MyClass<T,K> where T: IList, new() where K: Icomparable {              public void DoSomething() {                    T temp = new T();                    Debug.Assert(temp.Contains(“test”)); } }         VB .NET        Public Class MyClass(Of T As {New, IList}, K As IComparable)              Public Sub DoSomething()                    Dim temp As T = New T()                    Debug.Assert(temp.Contains(“test”))              End Sub        End Class
Constraints are specified by using the  where  contextual keyword  Constraint Description where T: struct The type argument must be a value type. Any value type except  Nullable  can be specified. See  Using Nullable Types (C# Programming Guide)  for more information. where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the  new()  constraint must be specified last.
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. Multiple interface constraints can be specified. The constraining interface can also be generic. where T : U The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
Which are simply methods that have type parameters. Generic methods are useful in many situations, particularly where you need the return type to be variable as in, e.g., factory methods. Methods are another exciting field of use for Generics. Generic methods will allow you to pass one or more data types.
C# public T DoSomething<T>(T input, string input2) {   T tempVar;  } VB .NET Public Function DoSomething(Of T)(ByVal input As T, _ ByVal input2 As String) As T              Dim tempVar As T;        End Function
System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following: Dictionary List Queue SortedDictionary Stack
Generics in VB.NET are very dangerous if you do not put  Option Strict On  at the beginning of your code or as your default in the configuration. VB.NET has a tendency to autocast if strict is not on
Generics has the following advantages: The Program becomes statically typed, so errors are discovered at compile-time. No runtime casts are required and the program runs faster. Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
Type Safe:  Generic types enforce compile-time type checking. This greatly reduces, if not eliminates, unhanded run-time exceptions due to data type conflicts Types based on  Object  accept any data type, and you must write code to check whether an input data type is acceptable. With generic types, the compiler can catch type mismatches before run time.
Re-usability :  A class written with Generics is reusable, no need duplicating classes for different data types Performance:  Since the data type is determined at compile-time there is no type casting at run-time Generic types do not have to  box  and  unbox  data, because each one is specialized for one data type.
Code Consolidation.   The code in a generic type has to be defined only once.  A set of type-specific versions of a type must replicate the same code in each version, with the only difference being the specific data type for that version.  With generic types, the type-specific versions are all generated from the original generic type.
Code Reuse.   Code that does not depend on a particular data type can be reused with various data types if it is generic. You can often reuse it even with a data type that you did not originally predict. Generic Algorithms. Abstract algorithms that are type-independent are good candidates for generic types. For example, a generic procedure that sorts items using the  IComparable  interface can be used with any data type that implements  IComparable .
IDE Support.   When you use a constructed type declared from a generic type, the integrated development environment (IDE) can give you more support while you are developing your code.  For example, IntelliSense can show you the type-specific options for an argument to a constructor or method.
Since generics without constraints are perceived by the compiler to be  System.Object  types, you cannot access any type members not available to  System.Object  nor can you use arithmetic operators or nested classes.  Cannot access static members or nested classes without explicitly casting.  Cannot use arithmetic operations unless the base class specified in the constraints list supports them. Cannot use generics themselves as type arguments, but, you can use constructed types as type arguments.
Creating Generic Type public class Col<T> { T t; public T Val{get{return t;}set{t=value;}}  There are a few things to notice.  The class name &quot;Col<T>&quot; is our first indication that this Type is generic. This Type placeholder &quot;T&quot; is used to show that if we need to refer to the actual Type that is going to be used when we write this class, we will represent it as &quot;T&quot;.  Notice on the next line the variable declaration &quot;T t;&quot; creates a member variable with the type of T, or the generic Type which we will specify later during construction of the class (it will actually get inserted by the Common Language Runtime (CLR) automatically for us).  The final item in the class is the public property. Again, notice that we are using the Type placeholder &quot;T&quot; to represent that generic type for the type of that property. Also notice that we can freely use the private variable &quot;t&quot; within the class.
Use of the Previous type in a Class public class ColMain  {  public static void Main()  { //create a string version of our generic class  Col<string> mystring = new Col<string>();  mystring.Val = &quot;hello&quot;; //output that value System.Console.WriteLine(mystring.Val); System.Console.WriteLine(mystring.Val.GetType()); //create another instance of our generic class, using a different type  Col<int> myint = new Col<int>();  myint.Val = 5;  System.Console.WriteLine(myint.Val);  System.Console.WriteLine(myint.Val.GetType());  }   }
For this example we want to be able to hold a collection of a Type that we create, which we used to represent a User in our system. Here is the definition for that class: namespace Rob  {  public class User  {  protected string name;  protected int age;  public string Name{get{return name;}set{name=value;}}  public int Age{get{return age;}set{age=value;}}  }   }
Now that we have our User defined, let's create an instance of the .NET Framework Generic version of a simple List:  System.Collections.Generic.List<Rob.User> users = new System.Collections.Generic.List<Rob.User>();  For ( int x=0;x<5;x++)  {  Rob.User user = new Rob.User(); user.Name=&quot;Rob&quot; + x;  user.Age=x; users.Add(user);  }
Public class Dictionary<K, V> where K : IComparable {}  Notice the &quot;where&quot; clause on this class definition. It is forcing the K Type to be of Type IComparable.  If K does NOT implement IComparable, you will get a Compiler error.
Another type of constraint is a constructor constraint:  public class Something<V> where V: new() {}
http://www.vbdotnetheaven.com http://www.c-sharpcorner.com http://www.15seconds.com www.15seconds.com  http://blogs.msdn.com/kcwalina
 

More Related Content

What's hot (19)

PPTX
Java script
Prarthan P
 
PPTX
Javascript functions
Alaref Abushaala
 
PPT
Java Script ppt
Priya Goyal
 
PPTX
Java script
Abhishek Kesharwani
 
PPTX
Placement and variable 03 (js)
AbhishekMondal42
 
PPTX
An Introduction to JavaScript
tonyh1
 
PPT
Introduction to JavaScript
Andres Baravalle
 
PPT
Learn javascript easy steps
prince Loffar
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPT
Introduction to jQuery
Andres Baravalle
 
PPTX
Javascript
Nagarajan
 
PPTX
Introduction to JavaScript Programming
Raveendra R
 
PPTX
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
PPTX
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
PPTX
Java script basics
Shrivardhan Limbkar
 
PPTX
Introduction to Javascript By Satyen
Satyen Pandya
 
PPT
Java script final presentation
Adhoura Academy
 
PPT
Java script -23jan2015
Sasidhar Kothuru
 
Java script
Prarthan P
 
Javascript functions
Alaref Abushaala
 
Java Script ppt
Priya Goyal
 
Java script
Abhishek Kesharwani
 
Placement and variable 03 (js)
AbhishekMondal42
 
An Introduction to JavaScript
tonyh1
 
Introduction to JavaScript
Andres Baravalle
 
Learn javascript easy steps
prince Loffar
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Introduction to jQuery
Andres Baravalle
 
Javascript
Nagarajan
 
Introduction to JavaScript Programming
Raveendra R
 
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
Java script basics
Shrivardhan Limbkar
 
Introduction to Javascript By Satyen
Satyen Pandya
 
Java script final presentation
Adhoura Academy
 
Java script -23jan2015
Sasidhar Kothuru
 

Viewers also liked (6)

PPTX
Geniies - Portfolio
Sankar Balasubramanian
 
PDF
Hari Sankar - Kusters Engineering India
Sankar Balasubramanian
 
PPS
Vb.net session 15
Niit Care
 
PPSX
Excel test
Sankar Balasubramanian
 
PPTX
Design half ,full Adder and Subtractor
[email protected].
 
Geniies - Portfolio
Sankar Balasubramanian
 
Hari Sankar - Kusters Engineering India
Sankar Balasubramanian
 
Vb.net session 15
Niit Care
 
Design half ,full Adder and Subtractor
[email protected].
 
Ad

Similar to Generics (20)

PPTX
Generics C#
Raghuveer Guthikonda
 
PPTX
Generics
Shahjahan Samoon
 
PPTX
Evolution of c# - by K.Jegan
talenttransform
 
PPTX
Back-2-Basics: .NET Coding Standards For The Real World
David McCarter
 
PPTX
Back-2-Basics: .NET Coding Standards For The Real World
David McCarter
 
PPT
VB.net
PallaviKadam
 
PPTX
Back-2-Basics: .NET Coding Standards For The Real World (2011)
David McCarter
 
PDF
C# interview-questions
nicolbiden
 
PPTX
Generic Programming in java
Garik Kalashyan
 
PPTX
Objects and Types C#
Raghuveer Guthikonda
 
PPTX
LEARN C# PROGRAMMING WITH GMT
Tabassum Ghulame Mustafa
 
PDF
Generics and collections in Java
Gurpreet singh
 
PPT
Generic
abhay singh
 
PPTX
Code Metrics
Attila Bertók
 
DOCX
Bca5020 visual programming
smumbahelp
 
DOCX
Bca5020 visual programming
smumbahelp
 
PDF
CSharp Advanced L05-Attributes+Reflection
Mohammad Shaker
 
PPTX
More Little Wonders of C#/.NET
BlackRabbitCoder
 
PPTX
Generics Module 2Generics Module Generics Module 2.pptx
AlvasCSE
 
Evolution of c# - by K.Jegan
talenttransform
 
Back-2-Basics: .NET Coding Standards For The Real World
David McCarter
 
Back-2-Basics: .NET Coding Standards For The Real World
David McCarter
 
VB.net
PallaviKadam
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
David McCarter
 
C# interview-questions
nicolbiden
 
Generic Programming in java
Garik Kalashyan
 
Objects and Types C#
Raghuveer Guthikonda
 
LEARN C# PROGRAMMING WITH GMT
Tabassum Ghulame Mustafa
 
Generics and collections in Java
Gurpreet singh
 
Generic
abhay singh
 
Code Metrics
Attila Bertók
 
Bca5020 visual programming
smumbahelp
 
Bca5020 visual programming
smumbahelp
 
CSharp Advanced L05-Attributes+Reflection
Mohammad Shaker
 
More Little Wonders of C#/.NET
BlackRabbitCoder
 
Generics Module 2Generics Module Generics Module 2.pptx
AlvasCSE
 
Ad

Recently uploaded (20)

PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
The Future of Artificial Intelligence (AI)
Mukul
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 

Generics

  • 1. ge⋅ner⋅ic –adjective  Also,  ge⋅ner⋅i⋅cal. 1. of, applicable to, or referring to all the members of a genus, class, group, or kind; general.
  • 2. “ Generic&quot;, unrelated to the programming world, it simply means something that is not tied to any sort of brand name. For example, if we purchase some generic dish soap, soap that has no brand name on it, we know that we are buying dish soap and expect it to help us clean our dishes. We can treat it as dish soap even though we don't really have any idea of its exact contents.
  • 3. Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. You can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations
  • 4. Generics are a new feature in version 2.0 of the common language runtime (CLR). Generics use the new keyword  Of By creating a generic class, you can create a collection that is type-safe at compile-time. Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot.
  • 5. The most basic type of a collection is an array; however, arrays can be difficult to use, particularly when the number of items in the array varies and when the actual items in the array vary or move around. To address these limitations, we have Collections, which are more or less friendly wrappers around arrays. More important, they enable us to interact with collections of types in a familiar way, just as we might interact with a collection of items in the real world.
  • 6. The problem with collections in the first version of .NET is that in order for them to be strongly typed, the developer would have to write custom collections for each and every type, overriding or implementing methods (such as Add, Remove, Contains, etc.) and indexers on each one Life was also hard for the computer because in order to generalize collection types enough, it had to use the Framework base class, Object, in order to provide the needed flexibility. Value types had to put them into a special package known as a boxing in order to store them in the collection (because the collection was of the Object type, which is a reference type).
  • 7. Any reference or value type that is added to an ArrayList is implicitly upcast to Object . If the items are value types, they must be boxed when they are added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations decrease performance ; the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collections
  • 8. The other limitation is lack of compile-time type checking; because an ArrayList casts everything to Object , there is no way at compile-time to prevent client code from doing something such as this:
  • 9. Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic  namespace. These should be used whenever possible in place of classes such as ArrayList  in the  System.Collections  namespace.
  • 10. Can create custom own generic interfaces, classes, methods, events and delegates. Generic classes may be constrained to enable access to methods on particular data types. Information on the types used in a generic data type may be obtained at run-time by means of reflection.
  • 11. What a &quot;type&quot; is in .NET   &quot;Type&quot; is simply short hand for &quot;type of data&quot; or &quot;data type&quot;; a type tells the computer how to store information (data) and what will be done with that information.   What Is meant by strongly typed? means that the computer has enough information-a clear blueprint-on how to deal with particular data 
  • 12. What is Type Parameter A type parameter is the core of enabling generic functionality. For types, it is kind of like a constructor parameter. For methods, it's like other parameters except that it can often be inferred
  • 13. What is Generic Type? A definition of a class, structure, interface, procedure, or delegate for which you supply at least one data type when you declare it. What is Generic method?  A generic method is any method that defines one or more type parameters, as in the DoSomething method It is important to note that generic methods do not have to be declared within generic types
  • 14. Type Parameter In a generic type definition, a placeholder for a data type you supply when you declare the type. Type Argument A specific data type that replaces a type parameter when you declare a constructed type from a generic type.
  • 15. Constraint A condition on a type parameter that restricts the type argument you can supply for it. A constraint can require that the type argument must implement a particular interface, be or inherit from a particular class, have an accessible parameter less constructor, or be a reference type or a value type. You can combine these constraints, but you can specify at most one class.
  • 16. What is Constructed Type? This means a type that is created (constructed) as a result of the usage of a generic type. A class, structure, interface, procedure, or delegate declared from a generic type by supplying type arguments for its type parameters. What are called Closed constructed types? At design-time we know the type that is being passed to it What are called open constructed types?
  • 17. C# public class MySample<T> {        public void DoSometing<K,V>()        {} } VB .NET Public Class MySample(Of T)        Public Sub DoSomething(Of K, V)()        End Sub End Class
  • 18. C# MySample<string> someSample; VB .NET someSample As MySample(Of String)
  • 19. C# public class MyExample<V>        {private MySample<V> someSample;} VB .NET      Public Class MyExample(Of V)        Private someSample As MySample(Of V)      End Class
  • 20. What is Constrain in .NET Generics? That enable the creator of a generic to specify that only certain types may be passed in as type arguments to his generic.
  • 21. C#        public class MyClass<T, K> {          public void DoSomething() {                    T temp = new T();                   Debug.Assert(temp.Contains(“test”)); }} VB .NET        Public Class MyClass(Of T, K)              Public Sub DoSomething()                    Dim temp As T = New T()                   Debug.Assert(temp.Contains(“test”))              End Sub        End Class
  • 22. C#        public class MyClass<T,K> where T: IList, new() where K: Icomparable {              public void DoSomething() {                    T temp = new T();                    Debug.Assert(temp.Contains(“test”)); } }         VB .NET        Public Class MyClass(Of T As {New, IList}, K As IComparable)              Public Sub DoSomething()                    Dim temp As T = New T()                    Debug.Assert(temp.Contains(“test”))              End Sub        End Class
  • 23. Constraints are specified by using the  where  contextual keyword Constraint Description where T: struct The type argument must be a value type. Any value type except  Nullable  can be specified. See  Using Nullable Types (C# Programming Guide)  for more information. where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the  new()  constraint must be specified last.
  • 24. 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. Multiple interface constraints can be specified. The constraining interface can also be generic. where T : U The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
  • 25. Which are simply methods that have type parameters. Generic methods are useful in many situations, particularly where you need the return type to be variable as in, e.g., factory methods. Methods are another exciting field of use for Generics. Generic methods will allow you to pass one or more data types.
  • 26. C# public T DoSomething<T>(T input, string input2) {   T tempVar; } VB .NET Public Function DoSomething(Of T)(ByVal input As T, _ ByVal input2 As String) As T              Dim tempVar As T;        End Function
  • 27. System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following: Dictionary List Queue SortedDictionary Stack
  • 28. Generics in VB.NET are very dangerous if you do not put  Option Strict On  at the beginning of your code or as your default in the configuration. VB.NET has a tendency to autocast if strict is not on
  • 29. Generics has the following advantages: The Program becomes statically typed, so errors are discovered at compile-time. No runtime casts are required and the program runs faster. Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
  • 30. Type Safe: Generic types enforce compile-time type checking. This greatly reduces, if not eliminates, unhanded run-time exceptions due to data type conflicts Types based on  Object  accept any data type, and you must write code to check whether an input data type is acceptable. With generic types, the compiler can catch type mismatches before run time.
  • 31. Re-usability : A class written with Generics is reusable, no need duplicating classes for different data types Performance: Since the data type is determined at compile-time there is no type casting at run-time Generic types do not have to  box  and  unbox  data, because each one is specialized for one data type.
  • 32. Code Consolidation.   The code in a generic type has to be defined only once. A set of type-specific versions of a type must replicate the same code in each version, with the only difference being the specific data type for that version. With generic types, the type-specific versions are all generated from the original generic type.
  • 33. Code Reuse.   Code that does not depend on a particular data type can be reused with various data types if it is generic. You can often reuse it even with a data type that you did not originally predict. Generic Algorithms. Abstract algorithms that are type-independent are good candidates for generic types. For example, a generic procedure that sorts items using the  IComparable  interface can be used with any data type that implements  IComparable .
  • 34. IDE Support.   When you use a constructed type declared from a generic type, the integrated development environment (IDE) can give you more support while you are developing your code. For example, IntelliSense can show you the type-specific options for an argument to a constructor or method.
  • 35. Since generics without constraints are perceived by the compiler to be System.Object types, you cannot access any type members not available to System.Object nor can you use arithmetic operators or nested classes. Cannot access static members or nested classes without explicitly casting. Cannot use arithmetic operations unless the base class specified in the constraints list supports them. Cannot use generics themselves as type arguments, but, you can use constructed types as type arguments.
  • 36. Creating Generic Type public class Col<T> { T t; public T Val{get{return t;}set{t=value;}} There are a few things to notice. The class name &quot;Col<T>&quot; is our first indication that this Type is generic. This Type placeholder &quot;T&quot; is used to show that if we need to refer to the actual Type that is going to be used when we write this class, we will represent it as &quot;T&quot;. Notice on the next line the variable declaration &quot;T t;&quot; creates a member variable with the type of T, or the generic Type which we will specify later during construction of the class (it will actually get inserted by the Common Language Runtime (CLR) automatically for us). The final item in the class is the public property. Again, notice that we are using the Type placeholder &quot;T&quot; to represent that generic type for the type of that property. Also notice that we can freely use the private variable &quot;t&quot; within the class.
  • 37. Use of the Previous type in a Class public class ColMain { public static void Main() { //create a string version of our generic class Col<string> mystring = new Col<string>(); mystring.Val = &quot;hello&quot;; //output that value System.Console.WriteLine(mystring.Val); System.Console.WriteLine(mystring.Val.GetType()); //create another instance of our generic class, using a different type Col<int> myint = new Col<int>(); myint.Val = 5; System.Console.WriteLine(myint.Val); System.Console.WriteLine(myint.Val.GetType()); } }
  • 38. For this example we want to be able to hold a collection of a Type that we create, which we used to represent a User in our system. Here is the definition for that class: namespace Rob { public class User { protected string name; protected int age; public string Name{get{return name;}set{name=value;}} public int Age{get{return age;}set{age=value;}} } }
  • 39. Now that we have our User defined, let's create an instance of the .NET Framework Generic version of a simple List: System.Collections.Generic.List<Rob.User> users = new System.Collections.Generic.List<Rob.User>(); For ( int x=0;x<5;x++) { Rob.User user = new Rob.User(); user.Name=&quot;Rob&quot; + x; user.Age=x; users.Add(user); }
  • 40. Public class Dictionary<K, V> where K : IComparable {} Notice the &quot;where&quot; clause on this class definition. It is forcing the K Type to be of Type IComparable. If K does NOT implement IComparable, you will get a Compiler error.
  • 41. Another type of constraint is a constructor constraint: public class Something<V> where V: new() {}
  • 43.