SlideShare une entreprise Scribd logo
1  sur  19
Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
.NET Generics
Generics
• Using Generics, we can create class templates that
support any type.
• Compile-time type checking

– By creating a generic class, you can create a collection that
is type-safe at compile-time.
– There is no need to write code to test for the correct data
type, because it is enforced at compile time
– The need for type casting and the possibility of run-time
errors are reduced.

• Binary code reuse

– Reuse same code with multiple types
– Generic code generated at run-time!
run-time
• Generics are classes, structures, interfaces, and
methods that have placeholders (type parameters)
for one or more of the types that they store or use.
• A generic collection class might use a type parameter
as a placeholder for the type of objects that it stores
• improved performance
• reduced code
simple generic class definition
•

public class Generic<T>
{
public T Field;
}
public static void Main()
{
Generic<string> g = new Generic<string>();
g.Field = "A string";
Console.WriteLine("Generic.Field = "{0}"", g.Field);
Console.WriteLine("Generic.Field.GetType() = {0}", g.Field.GetType().FullName);
}
Define and use a generic method
public class Method<T>
{
T[] item;
public void Test(T item)
{...}
}
Method<int> Test= new Method<int>();
Placeholders for Generic Types
• ƒ T…type
• ƒ K…key
• ƒ V…value
Applying Generics
• Generics may have any # of type parameters
Class Node<K, T>
{ public Node(K key, T item, Node<K, T>nextNode {….}
private K Key;
private T Item;
private Node<k, T> NextNode; }

• Must then instantiate with the # of parameters
Generic Interfaces
public interface ICalculator<T>
{
T Add(T param1, T param2);
}
public class SamCalculator : ICalculator<int>
{
public int Add(int arg1, int ar2)
{ return arg1 + arg2; }
}

• Interface declared with type parameters = a generic interface
declaration
Derivation Constraints
• Where reserved word to define a constraint
• Use where on generic type parameter followed by derivation
colon indicating generic type parameter implements
particular interface
public class LinkedList<K, T> where K : IComparable

• Overcome by new generic interface IComparable<T> in
System.Collections.Generics
• Constrain plus new interface eliminates boxing penalty:
public class LinkedList<K, T> where K : IComparable<K>
Derivation Constraints
• All constraints must appear after actual derivation list of
generic class
• Ex: If LinkedList<T> derives from IEnumerable<T>, put where
keyword after it:
public class LinkedList<K,T> : IEnumerable<T> where K :
IComparable<K>

• Can provide constraints for every generic type parameter
public class LinkedList<K, T> where K : IComparable<K>
where T : IClonable
Constructor Constraints
• Suppose want to instantiate new generic object inside generic
class
– C# compiler doesn’t know whether specific type you are going to use
has matching public default constructor
– Will not compile

• Constructor constraint makes possible for generic code to
create instances of type specified by constraining type args to
types that implement public default constructor
• Only default or parameterless constructors supported
Using Generics in the BCL
Enhancing the Base Library
Generic Collections
• System.Collections.Generic classes
–
–
–
–
–

List<T>
LinkedList<T>
Dictionary<K, V>
Stack<T>
Queue<T>

// new in Beta1!
// equivalent to non-generic HashTable

• System.Collections.Generic interfaces
–
–
–
–
–
–
–

IList<T>
IDictionary<K, V>
ICollection<T>
IEnumerable<T>
IEnumerator<T>
IComparable<T>
IComparer<T>

// replacement for IList
// replacement for IDictionary
// replacement for ICollection
// replacement for IEnumerable
// replacement for IEnumerator
// replacement for IComparable
// replacement for IComparer
Using Generics in the BCL
• All generic collections implement generic IEnumerable<T>
interface
• IEnumerable<T> provides access to IEnumerator<T> Iterators
interface, for abstracted iterations over collections (Think C++
STL Iterators)
Public interface IEnumerable<T>
{ IEnumerator<T> GetEnumerator(); }
Public interface IEnumerator<T> : IDisposable
{ T Current {get;}
bool MoveNext(); }
THANK YOU
If this presentation helped you, please visit our page
facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550

Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550

Contenu connexe

Tendances

Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Alexey Diyan
 
Type checking
Type checkingType checking
Type checkingrawan_z
 
Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Daniyal Mughal
 
Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Jamshid Hashimi
 
Primitives in Generics
Primitives in GenericsPrimitives in Generics
Primitives in GenericsIvan Ivanov
 
4. java intro class
4. java intro class4. java intro class
4. java intro classQuan Ho
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Jamshid Hashimi
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testingKnoldus Inc.
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharpNaved khan
 
An Introduction to ANTLR
An Introduction to ANTLRAn Introduction to ANTLR
An Introduction to ANTLRMorteza Zakeri
 
Keywords in python
Keywords in pythonKeywords in python
Keywords in pythonPushpakBhoge
 

Tendances (20)

Code quality
Code qualityCode quality
Code quality
 
Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...Using ANTLR on real example - convert "string combined" queries into paramete...
Using ANTLR on real example - convert "string combined" queries into paramete...
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
 
Type checking
Type checkingType checking
Type checking
 
Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6
 
Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2
 
Primitives in Generics
Primitives in GenericsPrimitives in Generics
Primitives in Generics
 
C# chap 4
C# chap 4C# chap 4
C# chap 4
 
C++
C++C++
C++
 
4. java intro class
4. java intro class4. java intro class
4. java intro class
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
 
Lecture02 java
Lecture02 javaLecture02 java
Lecture02 java
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharp
 
Linq
LinqLinq
Linq
 
An Introduction to ANTLR
An Introduction to ANTLRAn Introduction to ANTLR
An Introduction to ANTLR
 
Keywords in python
Keywords in pythonKeywords in python
Keywords in python
 
C# Generics
C# GenericsC# Generics
C# Generics
 

Similaire à Generics in dot net

Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxMarco Parenzan
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideNascenia IT
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3Duong Thanh
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending PythonPriyank Kapadia
 
Net framework session01
Net framework session01Net framework session01
Net framework session01Vivek chan
 
Game Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesGame Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesNick Pruehs
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureNick Pruehs
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.pptElieMambou1
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionMohammad Shaker
 
Windows 8 für .net Entwickler
Windows 8 für .net EntwicklerWindows 8 für .net Entwickler
Windows 8 für .net EntwicklerPatric Boscolo
 

Similaire à Generics in dot net (20)

Generic
GenericGeneric
Generic
 
Generics
GenericsGenerics
Generics
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
C#ppt
C#pptC#ppt
C#ppt
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3
 
Java
JavaJava
Java
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
 
Oops
OopsOops
Oops
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Game Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesGame Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design Principles
 
Java ce241
Java ce241Java ce241
Java ce241
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & Structure
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+Reflection
 
Windows 8 für .net Entwickler
Windows 8 für .net EntwicklerWindows 8 für .net Entwickler
Windows 8 für .net Entwickler
 

Plus de baabtra.com - No. 1 supplier of quality freshers

Plus de baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Dernier

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 

Dernier (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.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
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

Generics in dot net

  • 1.
  • 2. Disclaimer: This presentation is prepared by trainees of baabtra as a part of mentoring program. This is not official document of baabtra –Mentoring Partner Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt . Ltd
  • 4. Generics • Using Generics, we can create class templates that support any type. • Compile-time type checking – By creating a generic class, you can create a collection that is type-safe at compile-time. – There is no need to write code to test for the correct data type, because it is enforced at compile time – The need for type casting and the possibility of run-time errors are reduced. • Binary code reuse – Reuse same code with multiple types – Generic code generated at run-time! run-time
  • 5. • Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. • A generic collection class might use a type parameter as a placeholder for the type of objects that it stores • improved performance • reduced code
  • 6. simple generic class definition • public class Generic<T> { public T Field; } public static void Main() { Generic<string> g = new Generic<string>(); g.Field = "A string"; Console.WriteLine("Generic.Field = "{0}"", g.Field); Console.WriteLine("Generic.Field.GetType() = {0}", g.Field.GetType().FullName); }
  • 7. Define and use a generic method public class Method<T> { T[] item; public void Test(T item) {...} } Method<int> Test= new Method<int>();
  • 8. Placeholders for Generic Types • ƒ T…type • ƒ K…key • ƒ V…value
  • 9. Applying Generics • Generics may have any # of type parameters Class Node<K, T> { public Node(K key, T item, Node<K, T>nextNode {….} private K Key; private T Item; private Node<k, T> NextNode; } • Must then instantiate with the # of parameters
  • 10. Generic Interfaces public interface ICalculator<T> { T Add(T param1, T param2); } public class SamCalculator : ICalculator<int> { public int Add(int arg1, int ar2) { return arg1 + arg2; } } • Interface declared with type parameters = a generic interface declaration
  • 11. Derivation Constraints • Where reserved word to define a constraint • Use where on generic type parameter followed by derivation colon indicating generic type parameter implements particular interface public class LinkedList<K, T> where K : IComparable • Overcome by new generic interface IComparable<T> in System.Collections.Generics • Constrain plus new interface eliminates boxing penalty: public class LinkedList<K, T> where K : IComparable<K>
  • 12. Derivation Constraints • All constraints must appear after actual derivation list of generic class • Ex: If LinkedList<T> derives from IEnumerable<T>, put where keyword after it: public class LinkedList<K,T> : IEnumerable<T> where K : IComparable<K> • Can provide constraints for every generic type parameter public class LinkedList<K, T> where K : IComparable<K> where T : IClonable
  • 13. Constructor Constraints • Suppose want to instantiate new generic object inside generic class – C# compiler doesn’t know whether specific type you are going to use has matching public default constructor – Will not compile • Constructor constraint makes possible for generic code to create instances of type specified by constraining type args to types that implement public default constructor • Only default or parameterless constructors supported
  • 14. Using Generics in the BCL
  • 15. Enhancing the Base Library Generic Collections • System.Collections.Generic classes – – – – – List<T> LinkedList<T> Dictionary<K, V> Stack<T> Queue<T> // new in Beta1! // equivalent to non-generic HashTable • System.Collections.Generic interfaces – – – – – – – IList<T> IDictionary<K, V> ICollection<T> IEnumerable<T> IEnumerator<T> IComparable<T> IComparer<T> // replacement for IList // replacement for IDictionary // replacement for ICollection // replacement for IEnumerable // replacement for IEnumerator // replacement for IComparable // replacement for IComparer
  • 16. Using Generics in the BCL • All generic collections implement generic IEnumerable<T> interface • IEnumerable<T> provides access to IEnumerator<T> Iterators interface, for abstracted iterations over collections (Think C++ STL Iterators) Public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } Public interface IEnumerator<T> : IDisposable { T Current {get;} bool MoveNext(); }
  • 18. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 19. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: info@baabtra.com NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550

Notes de l'éditeur

  1. Type Checking - When we added an Int to our collection of type List, there is an implicit cast to Object. Similarly, if a int object is retrieved from the list, it must be cast at run time from an Object reference to a int reference. This lack of type safety at compile time is both tedious for the developer and prone to error. In contrast, when we used generics and our List&lt;itemType&gt; where itemType is typed to int causes all add and lookup methods to work with int references. This allows for specifying and checking the type of the elements at compile time rather than at run time. Binary code reuse- For maintenance purposes, a developer may elect to achieve compile-time type safety using List by deriving a StringList from it. The problem with this approach is that new code has to be written for every type for which you want a type-safe list, which can quickly become laborious. With List&lt;T&gt;, all you need to do is instantiate the type with the desired element type as T. As an added value, generics code is generated at run time, so two expansions over unrelated element types such as List&lt;String&gt; and List&lt;FileStream&gt; are able to reuse most of the same just-in-time (JIT)-compiled code. The CLR simply works out the details—no more code bloat! Performance - The bottom line is this: if type checking is done at compile time rather than at run time, performance improves. In managed code, casts between references and values incur both boxings and unboxings, and avoiding such casts can have an equally negative impact on performance. Current benchmarks of a quick-sort of an array of one million integers shows the generic method is three times faster than the non-generic equivalent. This is because boxing of the values is avoided completely. The same sort over an array of string references resulted in a 20 percent improvement in performance with the generic method due to the absence of a need to perform type checking at run time. Clarity – Clarity with generics comes in a number of forms. Constraints are a feature in generics that have the effect of making incompatible expansions of generic code impossible; with generics, you&apos;re never faced with the cryptic compiler errors that plague C++ template users. In the GenericSortedList&lt;T&gt; example, the collection class would have a constraint that makes it only work with types for T that can be compared and therefore sorted. Also, generic methods can often be called without employing any special syntax by using a feature called type inference. And, of course, type safety at compile time increases clarity in application code. I will look at constraints, type inference, and type safety in detail throughout this column.