Generics



  • These are known as General Data types
  • Using generics, we will write generic functions and generics classes
  • Generics are introduced in .NET framework version 2.0
  • Namespaces related to Generics are System.Collection.Generic, System.Collections.  Object Model, these namespaces contain generic collection classes that will allow working with Generic Types
  • Generic interfaces that will provide sorting and equality comparisons are present in System namespace
  • Generics can be implemented with classes, structures, interfaces, methods, Events and Delegates
  • The data types used in Generics can be obtained with the help of Reflection at runtime
  • Generics are used to avoid function overloading, when Data types of arguments are changed
  • To work with generics, we use two things,
  • Place holder represented by < >
  • Type parameter
  • Always type parameter should be enclosed within the place holder, like <type parameter>

Non-Generic Method


public Display(string S)
   {
          Code….
   }


Generic Method


public Display<G>(string S)
{
          Code…
}

Calling: Display<string>(“welcome”);
Calling: Display<int>(10);
Calling: Display<double>(10.5);
Passing Multiple Data Types to a Generic Function

In the above examples, we passed only single data type to generic function
If at all we want to pass multiple data types to a generic function at once, we declare the function like…
  Public void display <TP1,TP2>(TP1a, TP2b)
  {
          Code…
  }

Calling:

Display<int, int>(9,99.9);
Display<int, string>(9, “Sampath Kumar Vaddepally”);
Display<string, string>(“Vaddepally”,”Sampath”);

No comments:

Post a Comment