Generic in C #
Generic in C # allows you to delay the specification of the data type of programming elements in a class or method, until it is actually used in the program. In other words, Generic allows you to write a class or method that can work with any data type.
It is understandable that generic in C # is a data type, just like int data types, strings, . but different in that it is not a specific type but can be any type. With generics, reusable code more easily, the compiler catches errors easier and you no longer have to cast from objects.
You write specifications for classes and methods, with parameters that can replace data types. When the compiler encounters a constructor for a class or a function call for the method, it creates code to handle that specific data type. Here is a simple example that will help you understand this concept.
using System ; using System . Collections . Generic ; namespace Vd Generic { public class MyGenericArray < T > { private T [] array ; public MyGenericArray ( int size ) { array = new T [ size + 1 ]; } public T getItem ( int index ) { return array [ index ]; } public void setItem ( int index , T value ) { array [ index ] = value ; } } class Tester { static void Main ( string [] args ) { Console.WriteLine("Ví dụ về Generic trong C#");
Console.WriteLine("-------------------------"); //Khai báo mảng số nguyên. MyGenericArray intArray = new MyGenericArray ( 5 ); //Thiết lập giá trị. for ( int c = 0 ; c < 5 ; c ++) { intArray . setItem ( c , c * 5 ); } //Trích xuất giá trị. for ( int c = 0 ; c < 5 ; c ++) { Console . Write ( intArray . getItem ( c ) + " " ); } Console . WriteLine (); //Khai báo mảng ký tự. MyGenericArray charArray = new MyGenericArray ( 5 ); //Thiết lập giá trị. for ( int c = 0 ; c < 5 ; c ++) { charArray . setItem ( c , ( char )( c + 97 )); } //Trích xuất giá trị và in ra màn hình. for ( int c = 0 ; c < 5 ; c ++) { Console . Write ( charArray . getItem ( c ) + " " ); } Console . WriteLine (); Console . ReadKey (); } } }
Use the Console.ReadKey command (); to see the results more clearly.
Compile and run the C # program you will get the following result:
Example of Generic in C #
-------------------------
0 5 10 15 20
abcde
Features of Generic in C #
Generic is a technique that makes your C # program richer in the following ways:
- It helps you maximize code reuse, style safety, and performance.
- You can create generic collection classes. The .Net Framework class library contains some generic classes in System.Collections.Generic namespace. You can use these generic collection classes instead of the collection classes in System.Collections namespace.
- You can create classes, Interface, methods, Event and Delegate in generic form.
- You can create generic classes that have access to methods on specific data types.
- You can get information about the types used in a generic data type at runtime by Reflection methods.
Generic methods in C #
In the previous example, we used a generic class, similarly, we could declare a generic method with a type parameter. The following example illustrates this:
using System ; using System . Collections ; namespace QTMCsharp { class TestCsharp { static void Swap < T >( ref T lhs , ref T rhs ) { T temp ; temp = lhs ; lhs = rhs ; rhs = temp ; } static void Main ( string [] args ) { Console . WriteLine ( "Ví dụ 2 về Generic trong C#" ); Console . WriteLine ( "--------Ví dụ hoán đổi giá trị--------" ); int a , b ; char c , d ; a = 10 ; b = 20 ; c = 'I' ; d = 'V' ; // Hiển thị các giá trị trước khi hoán đổi. Console . WriteLine ( "Các giá trị số trước khi gọi hàm swap: " ); Console . WriteLine ( "a = {0}, b = {1}" , a , b ); Console . WriteLine ( "Các giá trị chữ trước khi gọi hàm swap:" ); Console . WriteLine ( "c = {0}, d = {1}" , c , d ); // Gọi hàm swap để hoán đổi giá trị. Swap ( ref a , ref b ); Swap ( ref c , ref d ); // Hiển thị các giá trị sau khi hoán đổi: Console . WriteLine ( "Các giá trị số trước khi gọi hàm swap:" ); Console . WriteLine ( "a = {0}, b = {1}" , a , b ); Console . WriteLine ( "Các giá trị chữ trước khi gọi hàm swap:" ); Console . WriteLine ( "c = {0}, d = {1}" , c , d ); Console . ReadKey (); } } }
Compiling and running the above C # program will produce the following results:
Example 2 of Generic in C #
-------- Value exchange example --------
The numeric values before calling the swap function:
a = 10, b = 20
Text values before calling the swap function:
c = I, d = V
The numeric values before calling the swap function:
a = 20, b = 10
Text values before calling the swap function:
c = V, d = I
Generic Delegate in C #
In C #, you can define a Generic Delegate with type parameters. For example:
delegate T NumberChanger < T >( T n );
The following example illustrates how to use the generic delegate in C #:
using System ; using System . Collections ; delegate T NumberChanger < T >( T n ); namespace QTMCsharp { class TestCsharp { static int num = 10 ; public static int AddNum ( int p ) { num += p ; return num ; } public static int MultNum ( int q ) { num *= q ; return num ; } public static int getNum () { return num ; } static void Main ( string [] args ) { Console . WriteLine ( "Generic Delegate trong C#" ); Console . WriteLine ( "---------------------------" ); //Tạo các đối tượng delegate NumberChanger nc1 = new NumberChanger ( AddNum ); NumberChanger nc2 = new NumberChanger ( MultNum ); //Gọi hai phương thức sử dụng các đối tượng delegate nc1 ( 25 ); Console . WriteLine ( "1 - Giá trị của num là: {0}" , getNum ()); nc2 ( 5 ); Console . WriteLine ( "2 - Giá trị của num là: {0}" , getNum ()); Console . ReadKey (); } } }
When running the above program, you will get the following result:
Generic Delegate in C #
---------------------------
1 - The value of num is: 35
2 - The value of num is: 175
According to Tutorialspoint
Previous article: Collection in C #
Next article: Anonymous method in C #
You should read it
- Google released Chrome 67 for Windows, Mac and Linux
- Template in C ++
- How to Change a User Account Picture in Windows 10
- Fix 'Generic Volume Cannot Be Stopped' error in Windows XP
- How to Edit a Dat File
- How to Install Open Source Software
- How to Set Up USB Game Controllers on Windows 8
- Risks from malware and how to prevent it
May be interested
- Risks from malware and how to prevent itthe article will focus on recent malware threats and suggest possible solutions to deal with these threats.
- List of default Windows key from Microsoftthe following article will provide rtm (retail) and kms key (default) lists for all windows 10 versions.
- How to set up a printer in Linuxprinting is something that most people look down on. that's a basic function of a pc, but when you switch to another platform, like linux, things can get complicated.
- Spotify Generic Melody Creation Guidespotify has added a new feature that lets you create shared tunes with others. the feature invites your friends to join, then creates a playlist for both of you.
- How to change the network configuration name in Windowsthe first time you configure and connect to the network, windows stores that information as a network configuration and names it the most generic name such as network, network 1, etc. if there are multiple networks, names the default may cause confusion for users. this article will show you how to change the network configuration name.
- Germany: Buy Samsung Wave to be 'promoted' malicious codesome security companies have warned users that a file called s8500 on microsd memory cards with samsung wave phones is actually a trojan.
- The Linux Foundation announced the release of ACRN - an open source virtual machine project for IoT devicesthe linux foundation has just announced a new project called acrn, which provides generic code to create hypervisors for iot devices.
- Trojan hidden in Compatibility Checker Windows 7, Safari sticks to security errorsa type of trojan hidden in the system to check the compatibility of the system with windows 7 has just been discovered.
- Quickly download new drivers through Device Manager on Windows 10on windows 10, drivers are needed for your device to connect with other devices and the operating system. windows 10 provides a series of default generic drivers for monitors (displays), wireless connections such as bluetooth, keyboards, mice, and other manufacturer-installed hardware.
- Instructions to turn off Smart Punctuation on iPhone and iPadsmart punctuation is a feature of ios, which automatically converts generic punctuation marks into better types of punctuation. for example, parentheses turn into quotation marks. the problem is that this feature does not always work well.