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:
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.
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
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>()
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.