SlideShare a Scribd company logo
1 of 27
C# Generics
PraveenKumar.M,
Xamarin developer
Topics to be covered
• What is Generics?
• Overview of Generics.
• Generics in detail.
What is Generics?
Generics is just one of the coding styles which can be used in C#
development. It provides,
• Type-safety
• Performance improvement.
• Higher quality of code -(Reusablitiy in data processing algorithms).
What is Type-safety?
Type safe language
• A programming language which doesn't allow the developer to set one type
of data with other type of data is said to be a type safe language.
• Eg: C#,Java.
• Javascript is an example of Non-Type-Safe language.
• JavaScript are not type safe because they allow you to set one type of data
with other type of data.
• Example:
Output will be : 1212
So what happens when you do the same
process in C#?
If you try to do the same concatenation on C#, with well defined types,the compiler
throws type mismatch error.
So to match the respective variable type, either Integer should ne converted
into string or vice versa.
• In this case most of the errors were spotted at the compile time iteself.
• This makes the developers to write well managed code.
Performace Improvement
Without using Generics
• For example if you need to store a collection of different data types without
generics, there is no class exist except “ArrayList”.
ArrayList:
You can add any value to an arraylist regardless of datatypes.
Eg:
var m_arraylist = new ArrayList();
m_arraylist.Add(123);
m_arraylist.Add(“Sample”);
m_arraylist.Add(obj);
• By default the values are implicitly boxed into object while storing into the list.
• If you wanna do some operations with the ArrayList items, it should be unboxed
with their respective data types.
• So to overcome this drawback we can use Generics since Boxing and Unboxing is
expensive computationally.
Note:
When a value type is boxed, an entirely new instance object must be
allocated and constructed.
Objects -----> Heap memory.
Values -----> Stack memory.
Without Generics With Generics
List<object> list1 = new List<object>();
// No boxing, no casting:
list1.Add(3);
list1.Add(“It is raining in Redmond.”);
The values here are boxed into objects and it
should be unboxed later.
Generic class:
public class GenericList<T>
{
void Add(T input){}//Add our custom methods
}
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type ExampleClass
GenericList<ExampleClass> obj = new
GenericList<ExampleClass>();
Actual values are stored here rather than a reference to
objects that contain the values. Therefore no boxing is
required.
Concepts covered till now:
1. Type safety
2. Performance
Reusability
• Generics allows the developers to write a class and methods such as lists,queues
and so on to be defined with a type T as a parameter.
public class GenericList<T>
{
}
Generics concepts to be covered
• Generic Methods
• Generic Classes
• Generic Constraints
• Generic Interfaces
Generic Methods
public static bool Compare<T>(T value, T value2)
{
return value.Equals(value2);
}
Generic Classes
Generic Constraint
Here the parameter T should only be of a reference type and so value types are not
allowed.
Eg: If you try to initialize the class with 'int',
//Compilation error:
Lesson<int> stringLesson = new Lesson<int>();
//Compilation will be successful:
Lesson<string> obj = new Lesson<string>()
Generic Interfaces
If you creating object for “Book” class with “String” as parameter, it will
create the following class with following interface, then we will use the add
method to add the string value to the Book class.
Thank you..!

More Related Content

What's hot

Intorudction into VBScript
Intorudction into VBScriptIntorudction into VBScript
Intorudction into VBScript
Vitaliy Ganzha
 
Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVA
Jai Marathe
 

What's hot (17)

Vb script
Vb scriptVb script
Vb script
 
Intorudction into VBScript
Intorudction into VBScriptIntorudction into VBScript
Intorudction into VBScript
 
Vb script
Vb scriptVb script
Vb script
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
Overview of Adaptive Blocking for DDL Research Lab
Overview of Adaptive Blocking for DDL Research LabOverview of Adaptive Blocking for DDL Research Lab
Overview of Adaptive Blocking for DDL Research Lab
 
How do you delete an element from an options array? a) Set it to false. ...
How do you delete an element from an options array?     a) Set it to false.  ...How do you delete an element from an options array?     a) Set it to false.  ...
How do you delete an element from an options array? a) Set it to false. ...
 
Vbscript
VbscriptVbscript
Vbscript
 
Java Variable Types
Java Variable TypesJava Variable Types
Java Variable Types
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
Learn To Code: Introduction to c
Learn To Code: Introduction to cLearn To Code: Introduction to c
Learn To Code: Introduction to c
 
Intro to Ruby Variables
Intro to Ruby VariablesIntro to Ruby Variables
Intro to Ruby Variables
 
Static keyword a.z
Static keyword a.zStatic keyword a.z
Static keyword a.z
 
Extracts from "Clean Code"
Extracts from "Clean Code"Extracts from "Clean Code"
Extracts from "Clean Code"
 
Extracts from "Clean Code"
Extracts from "Clean Code"Extracts from "Clean Code"
Extracts from "Clean Code"
 
Basic vbscript for qtp
Basic vbscript for qtpBasic vbscript for qtp
Basic vbscript for qtp
 
Why Static Type Checking is Better
Why Static Type Checking is BetterWhy Static Type Checking is Better
Why Static Type Checking is Better
 
Generics of JAVA
Generics of JAVAGenerics of JAVA
Generics of JAVA
 

Similar to C# Generics

Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
TawnaDelatorrejs
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
Saurabh Narula
 

Similar to C# Generics (20)

Generics
GenericsGenerics
Generics
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Generics
GenericsGenerics
Generics
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
12.6-12.9.pptx
12.6-12.9.pptx12.6-12.9.pptx
12.6-12.9.pptx
 
Typescript
TypescriptTypescript
Typescript
 
Introduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviIntroduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston Levi
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.net
 
I x scripting
I x scriptingI x scripting
I x scripting
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programming
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programming
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
 
3 jf h-linearequations
3  jf h-linearequations3  jf h-linearequations
3 jf h-linearequations
 

Recently uploaded

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid Environments
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

C# Generics

  • 2. Topics to be covered • What is Generics? • Overview of Generics. • Generics in detail.
  • 3. What is Generics? Generics is just one of the coding styles which can be used in C# development. It provides, • Type-safety • Performance improvement. • Higher quality of code -(Reusablitiy in data processing algorithms).
  • 5. Type safe language • A programming language which doesn't allow the developer to set one type of data with other type of data is said to be a type safe language. • Eg: C#,Java. • Javascript is an example of Non-Type-Safe language.
  • 6. • JavaScript are not type safe because they allow you to set one type of data with other type of data. • Example:
  • 7. Output will be : 1212
  • 8. So what happens when you do the same process in C#?
  • 9. If you try to do the same concatenation on C#, with well defined types,the compiler throws type mismatch error.
  • 10. So to match the respective variable type, either Integer should ne converted into string or vice versa.
  • 11. • In this case most of the errors were spotted at the compile time iteself. • This makes the developers to write well managed code.
  • 13. Without using Generics • For example if you need to store a collection of different data types without generics, there is no class exist except “ArrayList”. ArrayList: You can add any value to an arraylist regardless of datatypes. Eg: var m_arraylist = new ArrayList(); m_arraylist.Add(123); m_arraylist.Add(“Sample”); m_arraylist.Add(obj);
  • 14. • By default the values are implicitly boxed into object while storing into the list. • If you wanna do some operations with the ArrayList items, it should be unboxed with their respective data types. • So to overcome this drawback we can use Generics since Boxing and Unboxing is expensive computationally. Note: When a value type is boxed, an entirely new instance object must be allocated and constructed. Objects -----> Heap memory. Values -----> Stack memory.
  • 15. Without Generics With Generics List<object> list1 = new List<object>(); // No boxing, no casting: list1.Add(3); list1.Add(“It is raining in Redmond.”); The values here are boxed into objects and it should be unboxed later. Generic class: public class GenericList<T> { void Add(T input){}//Add our custom methods } GenericList<int> list1 = new GenericList<int>(); // Declare a list of type ExampleClass GenericList<ExampleClass> obj = new GenericList<ExampleClass>(); Actual values are stored here rather than a reference to objects that contain the values. Therefore no boxing is required.
  • 16. Concepts covered till now: 1. Type safety 2. Performance
  • 17. Reusability • Generics allows the developers to write a class and methods such as lists,queues and so on to be defined with a type T as a parameter. public class GenericList<T> { }
  • 18. Generics concepts to be covered • Generic Methods • Generic Classes • Generic Constraints • Generic Interfaces
  • 19. Generic Methods public static bool Compare<T>(T value, T value2) { return value.Equals(value2); }
  • 21.
  • 23. Here the parameter T should only be of a reference type and so value types are not allowed. Eg: If you try to initialize the class with 'int', //Compilation error: Lesson<int> stringLesson = new Lesson<int>(); //Compilation will be successful: Lesson<string> obj = new Lesson<string>()
  • 25.
  • 26. If you creating object for “Book” class with “String” as parameter, it will create the following class with following interface, then we will use the add method to add the string value to the Book class.