SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Generics Ch. Vishwa Mohan Freelance Software Consultant & Corporate Trainer
Generics Generics are similar to C++ templates. Generics has the following features:  Type Safety,  No boxing and unboxing when using collections for value types.  No Downcasts.   Generic types can be defined in one language and used from any other .NET languages (Binary code reuse).  Reduced Code bloat (typed collections). Instantiated at run-time not compile time.  Work for both reference and value types.  Complete run-time type information.  It is not possible to assign null to generic types. In this case the keyword default can be used.
Generics  Type parameter can be applied to  Classes Structures Interfaces  Delegates You can also apply type parameters to methods also Type parameters can have constraints (See next slide).  Some more info on Generics: T.default Null Checks Type Casts
Generic Class Features It is not possible to assign null to generic types. In this case the keyword default can be used.  T   obj = default(T);   //Initializing to default.  You can apply constraints on generic types.  public MyGenericType<T> where T : IEnumerable {  ..,  }  Generics supports some more constraints as follow: where T : struct //This constrain says type T must be value type.  where T : class // This constrain says type T must be reference type.  where T : Foo   //T is required to be derived from base class Foo.  where T : new() // Specifies T must have default ctor. Constructor Constraint. where T : V   //The type T derived from a generic type V. This constraint 	            // is known as  “Naked Type Constraint”. You can also combine multiple constraints: public class MyClass<T>where T : IFoo, new() //Here T implements IFoo and have default constructor.
Generics Inheritance in Generics:  A generic type can implement a generic interface. Similarly generic class can be derived from a generic base class provided it must follow the below requirement.  Generic type of the interface must be repeated or the type of the base class must be specified.  Static Members: Static members of a generic class are only shared with one instantiation of the class.  There is separate instance of the static variable exist for each type parameter.  Generic Interfaces: Using generics you can define interfaces that defines methods with generic parameters.  Generic Methods: Like C++, it is also possible to generic methods. Here generic type is define with method declaration.  void Swap<T>(ref T x,   ref T y) {  …,} 		Swap<int>(ref i, ref j);   //Invoking a generic method.
Generic Delegates With generic delegates the parameter of the delegate can be defined later. Simple delegate examples is given below:  public delegate void Del<T>(T item);  public delegateT2  Action<T1, T2>(T1  tVal);  Nullable<T>: Suppose if you are instantiated as Nullable<int> x. The variable x can now be used like int and also you can assign null to it. Nullable<int> x; //or int? x; 		if(x.HasValue) 		x = 5;					     int y = x.Value;  		x += 20; 					  x = null; EventHandler<TEventArgs>: With Windows forms, Web Applications delegates many different event handlers are defined.  ArraySegment<T>:  This structure is used to represent a segment of an array. The offset and count of segment is stored in this structure.  Benefit of ArraySegment is you can pass it to method as a argument.  Take note, ArraySegment don’t make copy of elements of array. It just refers it.
Thank You !

Weitere ähnliche Inhalte

Was ist angesagt?

#OOP_D_ITS - 8th - Class Diagram
#OOP_D_ITS - 8th - Class Diagram#OOP_D_ITS - 8th - Class Diagram
#OOP_D_ITS - 8th - Class Diagram
Hadziq Fabroyir
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
Deepak Singh
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
asadsardar
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
 

Was ist angesagt? (20)

Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
#OOP_D_ITS - 8th - Class Diagram
#OOP_D_ITS - 8th - Class Diagram#OOP_D_ITS - 8th - Class Diagram
#OOP_D_ITS - 8th - Class Diagram
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Generics
GenericsGenerics
Generics
 
Regular expressions for JavaScript
Regular expressions for JavaScriptRegular expressions for JavaScript
Regular expressions for JavaScript
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Total oop in c# dot net
Total oop in c# dot netTotal oop in c# dot net
Total oop in c# dot net
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Interface
InterfaceInterface
Interface
 
C keywords and identifiers
C keywords and identifiersC keywords and identifiers
C keywords and identifiers
 
Friend Function
Friend FunctionFriend Function
Friend Function
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
datatypes_variables_constants
datatypes_variables_constantsdatatypes_variables_constants
datatypes_variables_constants
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 

Andere mochten auch

Andere mochten auch (7)

Generics n delegates
Generics n delegatesGenerics n delegates
Generics n delegates
 
Javascript
JavascriptJavascript
Javascript
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturte
 
Controls
ControlsControls
Controls
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
Ajaxppt
AjaxpptAjaxppt
Ajaxppt
 

Ähnlich wie Generics

Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
Gautam Roy
 

Ähnlich wie Generics (20)

Generics
GenericsGenerics
Generics
 
Generics C#
Generics C#Generics C#
Generics C#
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
Generics
GenericsGenerics
Generics
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Java generics(Under The Hood Of The Compiler) by Harmeet singh
Java generics(Under The Hood Of The Compiler) by Harmeet singhJava generics(Under The Hood Of The Compiler) by Harmeet singh
Java generics(Under The Hood Of The Compiler) by Harmeet singh
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Generics_RIO.ppt
Generics_RIO.pptGenerics_RIO.ppt
Generics_RIO.ppt
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dart
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 

Mehr von Iblesoft

Master pages ppt
Master pages pptMaster pages ppt
Master pages ppt
Iblesoft
 
State management
State managementState management
State management
Iblesoft
 
State management
State managementState management
State management
Iblesoft
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls ppt
Iblesoft
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
Iblesoft
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architecture
Iblesoft
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
Iblesoft
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 

Mehr von Iblesoft (10)

Master pages ppt
Master pages pptMaster pages ppt
Master pages ppt
 
State management
State managementState management
State management
 
State management
State managementState management
State management
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls ppt
 
Ado.net
Ado.netAdo.net
Ado.net
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architecture
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Html ppt
Html pptHtml ppt
Html ppt
 
Exception handling
Exception handlingException handling
Exception handling
 

Kürzlich hochgeladen

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Kürzlich hochgeladen (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Generics

  • 1. Generics Ch. Vishwa Mohan Freelance Software Consultant & Corporate Trainer
  • 2. Generics Generics are similar to C++ templates. Generics has the following features: Type Safety, No boxing and unboxing when using collections for value types. No Downcasts. Generic types can be defined in one language and used from any other .NET languages (Binary code reuse). Reduced Code bloat (typed collections). Instantiated at run-time not compile time. Work for both reference and value types. Complete run-time type information. It is not possible to assign null to generic types. In this case the keyword default can be used.
  • 3. Generics Type parameter can be applied to Classes Structures Interfaces Delegates You can also apply type parameters to methods also Type parameters can have constraints (See next slide). Some more info on Generics: T.default Null Checks Type Casts
  • 4. Generic Class Features It is not possible to assign null to generic types. In this case the keyword default can be used. T obj = default(T); //Initializing to default. You can apply constraints on generic types. public MyGenericType<T> where T : IEnumerable { .., } Generics supports some more constraints as follow: where T : struct //This constrain says type T must be value type. where T : class // This constrain says type T must be reference type. where T : Foo //T is required to be derived from base class Foo. where T : new() // Specifies T must have default ctor. Constructor Constraint. where T : V //The type T derived from a generic type V. This constraint // is known as “Naked Type Constraint”. You can also combine multiple constraints: public class MyClass<T>where T : IFoo, new() //Here T implements IFoo and have default constructor.
  • 5. Generics Inheritance in Generics: A generic type can implement a generic interface. Similarly generic class can be derived from a generic base class provided it must follow the below requirement. Generic type of the interface must be repeated or the type of the base class must be specified. Static Members: Static members of a generic class are only shared with one instantiation of the class. There is separate instance of the static variable exist for each type parameter. Generic Interfaces: Using generics you can define interfaces that defines methods with generic parameters. Generic Methods: Like C++, it is also possible to generic methods. Here generic type is define with method declaration. void Swap<T>(ref T x, ref T y) { …,} Swap<int>(ref i, ref j); //Invoking a generic method.
  • 6. Generic Delegates With generic delegates the parameter of the delegate can be defined later. Simple delegate examples is given below: public delegate void Del<T>(T item); public delegateT2 Action<T1, T2>(T1 tVal); Nullable<T>: Suppose if you are instantiated as Nullable<int> x. The variable x can now be used like int and also you can assign null to it. Nullable<int> x; //or int? x; if(x.HasValue) x = 5; int y = x.Value; x += 20; x = null; EventHandler<TEventArgs>: With Windows forms, Web Applications delegates many different event handlers are defined. ArraySegment<T>: This structure is used to represent a segment of an array. The offset and count of segment is stored in this structure. Benefit of ArraySegment is you can pass it to method as a argument. Take note, ArraySegment don’t make copy of elements of array. It just refers it.