Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

Generics and its types in C# programming 

Generics and its types in c#


Generics

Generics are a kind of parameterized data structures that can work with value types as well as reference types. You can define a class, interface, structure, method, or delegate as a generic type in c#.

Consider a C# program that uses an array variable of type Object to store a collection of students The names are read from the console as value types and are boxed to enable storing each of them as a type object. In this case, the compiler cannot verify the data stored against its data type as it allows you to cast any value to and from the object. If you enter numeric data, it will be accepted without verification.

To ensure type safety, C# introduces generics, which has several features including the ability to allow you to define generalized type templates based on which the type can be constructed later.


1. Namespaces, Classes, and Interfaces for Generics

There are several namespaces in the .NET Framework that facilitate the creation and use of generics.

The System. Collections.ObjectModel namespace allows you to create dynamic and read-only generic collections. The System. Collections. Generic namespace consists of classes and interfaces that allow you to define customized generic collections.

Classes:-

The System. Collections. Generic namespace consists of classes that allow you to create type-safe collections. Some of the widely used classes of the System.Collections. Generics namespace.

  • Comparer: This is an abstract class that allows you to create a generic collection by implementing the functionalities of the IComparer interface
  • Dictionary. KeyCollection: Consists of keys present in the instance of the Dictionary class
  • Dictionary. Value Collection: Consists of values present in the instance of the Dictionary class
  • Equality Comparer: This is an abstract class that allows you to create a generic collection by implementing the functionalities of the IEqual ityComparer interface

Interfaces:-

The System. Collections. Generic namespace consists of interfaces that allow you to create type-safe collections. Some of the widely used interfaces of the System.Collections.Generics namespace.

  • IComparer: Defines a generic method compare () that compares values within a collection
  • IEnumerable: Defines a generic method GetEnumerator () that iterates over a collection
  • IEqualityComparer: Consists of methods that check for the equality between two objects

2. System. Collections. ObjectModel

The System. Collections.ObjectModel namespace consists of classes that can be used to create customized generic collections.

  • Collection<>: Provides the base class for generic collections
  • KeyedCollection<>: Provides an abstract class for a collection whose keys are associated with values
  • ReadOnlyCollection<>: Is a read-only generic base class that prevents modification of collection

3. Creating Generic Types

A generic declaration always accepts a type parameter, which is a placeholder for the required data type. The type is specified only when a generic type is referred to or constructed as a type within a program.

The process of creating a generic type begins with a generic type definition containing type parameters. The definition acts like a blueprint. Later, a generic type is constructed from the definition by specifying actual types as the generic type arguments, which will substitute for the type parameters or the placeholders.


5. Benefits

Generics ensure type safety at compile-time. Generics allow you to reuse the code safely without casting or boxing. A generic type definition is reusable with different types but can accept values of a single type at a time. Apart from reusability, there are several other benefits of using generics.

These are as follows:

  • Improved performance because of low memory usage as no casting or boxing operation is required to create a generic
  • Ensured strongly-typed programming model
  • Reduced run-time errors that may occur due to casting or boxing

=================


Creating and Using Generics

Generic types are not confined to classes alone but can include interfaces and delegates. This section examines generic classes, methods, interfaces, delegates, and so on.


1. Generic Classes

Generic classes define functionalities that can be used for any data type. Generic classes are declared with a class declaration followed by a type parameter enclosed within angular brackets. While declaring a generic class, you can apply some restrictions or constraints to the type parameters by using the where keyword. However, applying constraints to the type parameters is optional.

Thus, while creating a generic class, you must generalize the data types into the type parameter and optionally decide the constraints to be applied to the type parameter.

Note: Generic classes can be nested within other generic or non-generic classes. However, any class nested within a generic class is itself a generic class since the type parameters of the outer class ars supplied to the nested class.


2. Constraints on Type Parameters

You can apply constraints on the type parameter while declaring a generic type. A constraint is a restriction imposed on the data type of the type parameter. Constraints are specified using the where keyword They are used when the programmer wants to limit the data types of the type parameter to ensure consistency and reliability of data in a collection.

Types of constraints that can be applied to the type parameter.

  • T: Struct: Specifies that the type parameter must be of a value type only except the null value
  • T: Class: Specifies that the type parameter must be of a reference type such as a class, interface, or delegate
  • T: new (): Specifies that the type parameter must consist of a constructor without any parameter that can be invoked publicly
  • T: <base class name>: Specifies that the type parameter must be the parent class or should inherit from a parent class
  • T: <interface name>: Specifies that the type parameter must be an interface or should inherit an interface

Note: When you use a certain type as a constraint, the type used as a constraint must have a greater scope of accessibility than the generic type that will be using the constraint.


3. Inheriting Generic Classes

A generic class can be inherited like any other non-generic class in C#. Thus, a generic class is a base class or a derived class.

While inheriting a generic class in another generic class, you can use the generic type parameter of the base class instead of passing the data type of the parameter. However, while inheriting a generic class in a non-generic class, you must provide the data type of the parameter instead of the base class generic type parameter. The constraints imposed at the base class level must be included in the derived generic class.


4. Generic Methods

Generic methods process values whose data types are known only when accessing the variables that store these values. A generic method is declared with the generic type parameter list enclosed within angular brackets. Defining methods with type parameters allows you to call the method with a different type every time. You can declare a generic method within generic or non-generic class declarations. When you declare a generic method within a generic class declaration, the body of the method refers to the type parameters of both, the method and class declaration.

Generic methods can be declared with the following keywords:

  • virtual: The generic methods declared with the virtual keyword can be overridden in the derived class.

  • override: The generic method declared with the override keyword overrides the base class method. However, while overriding, the method does not specify the type parameter constraints since the constraints are overridden from the overridden method.

  • abstract: The generic method declared with the abstract keyword contains only the declaration of the method. Such methods are typically implemented in a derived class.

5. Generic Interfaces

Generic interfaces are useful for generic collections or generic classes representing the items in the collection. You can use the generic classes with the generic interfaces to avoid boxing and unboxing operations on the value types.

Generic classes can implement the generic interfaces by passing the required parameters specified in the interface. Similar to generic classes, generic interfaces also implement inheritance.


6. Generic Interface Constraints

You can specify an interface as a constraint on a type parameter. This enables you to use the members of the interface within the generic class. In addition, it ensures that only the types that implement the interface are used.


7. Generic Delegates

Delegates are reference types that encapsulate a reference to a method that has a signature and a return type. Similar to classes, interfaces, and structures, user-defined methods and delegates can also be declared as generic. A generic delegate can be used to refer to multiple methods in a class with different types of parameters. However, the number of parameters of the delegate and the referenced methods must be the same. The syntax for declaring a generic delegate is similar to that of declaring a generic method, where the type parameter list is specified after the delegate's name.


8. Overloading Methods Using Type Parameters

Methods of a generic class that takes generic type parameters can be overloaded. The programmer overloads the methods that use type parameters by changing the type or the number of parameters. However, the type difference is not based on the generic type parameter, but is based on the data type of the parameter passed.


9. Overriding Virtual Methods in Generic Class

Methods in generic classes can be overridden like the method in any non-generic class. To override a method in the generic class, the method in the base class must be declared as virtual and this method can be overridden in the derived class, using the override keyword.



C# Generics in c# Generics and its types in c# generics in c# with example generic method in c# c# generic method where t c# generic class c# generic method return type generic method and non-generic class in c# namespace classes and interfaces for generi

advertisement