Зміст курсу
Advanced C# with .NET
Advanced C# with .NET
1. Introduction to Desktop Development with .NET
What are Generics?
The term Generic means "general" or "collective". In terms of C# programming, generic means "not specific to a particular (data) type".
Generics are a way to add flexibility to our code and make it more robust. By creating a generic class, we can leave the data types of its fields, properties, method parameters, or even method return as undecided or generic, and they can be later filled by any data type which can be decided at the time of object creation. We can look at examples to understand this concept better.
The System.Collections.Generic
namespace contains some generic-based collection classes such as Lists and Dictionaries. We had already looked at the syntax for creating and using Lists and Dictionaries.
Following is the syntax for creating a new list object:
index
Similarly, following is the syntax for creating a new dictionary object:
index
We already know that the basic syntax for creating a new object of a class is new ClassName(arg1, …);
. However, in the case of List and Dictionary, there are data types enclosed in angle brackets (<
, >
).
This is because both List and Dictionary are generic-based types or classes, and therefore they allow the flexibility of creating objects that can support any datatype. Hence, we are able to create lists and dictionaries which can store values of any data type including int
, float
, double
, bool
or even objects of our own classes:
index
It would have been tedious and inefficient if the List
and Dictionary
classes were implemented without using Generics. Perhaps, there would've been multiple different classes to support different data types, or some complicated logic inside a single class which enables support for multiple data types at the cost of type safety increasing the risk of runtime errors.
In fact, there is an older version of the List class still available in the System.Collections
namespace, known as ArrayList
, which is a non-generic class and hence it is prone to runtime errors. In the Microsoft documentation, it has been discouraged to use ArrayList
however it is still included in the recent versions of C# to keep the backwards compatibility with older programs.
Generics provide a neat method of supporting multiple data types from a single class, hence improving the code reusability, efficiency and type safety.
The data type(s) which we pass between the angle brackets are known as generic type parameters, or simply type parameters.
Все було зрозуміло?