Generic means the general size, not specific. In C#, generic means not specific khổng lồ a particular data type.

C# allows you to define generic classes, interfaces, abstract classes, fields,methods, static methods, properties, events, delegates, & operators using the type parameter & without the specific data type. A type parameter is a placeholder for a particular type specified when creating an instance of the generic type.

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName where T is a type parameter.

Generic Class

Generic classes are defined using a type parameter in an angle brackets after the class name. The following defines a generic class.

Example: Define Generic Class

class DataStoreT> public T Data get; set;
Above sầu, the DataStore is a generic class. T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, & delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.

cảnh báo
It is not required to use T as a type parameter. You can give any name khổng lồ a type parameter. Generally, T is used when there is only one type parameter. It is recommended to lớn use a more readable type parameter name as per requirement lượt thích TSession, TKey, TValue etc. Learn more about Type Parameter Naming Guidelines

You can also define multiple type parameters separated by a comma.

Example: Generic Class with Multiple Type Parameters

class KeyValuePairTKey, TValue> public TKey Key get; set; public TValue Value get; set;

Instantiating Generic Class

You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore.

Bạn đang xem: Generic c# là gì

DataStorestring> store = new DataStorestring>();
Above, we specified the string type in the angle brackets while creating an instance. So, T will be replaced with a string type wherever T is used in the entire class at compile-time. Therefore, the type of Data property would be a string.

The following figure illustrates how generics works.


You can assign a string value khổng lồ the Data property. Trying to lớn assign values other than string will result in a compile-time error.

DataStorestring> store = new DataStorestring>();store.Data = "Hello World!";//obj.Data = 123; //compile-time error
You can specify the different data types for different objects, as shown below.

Example: Generic class

DataStorestring> strStore = new DataStorestring>();strStore.Data = "Hello World!";//strStore.Data = 123; // compile-time errorDataStoreint> intStore = new DataStoreint>();intStore.Data = 100;//intStore.Data = "Hello World!"; // compile-time errorKeyValuePairint, string> kvp1 = new KeyValuePairint, string>();kvp1.Key = 100;kvp1.Value = "Hundred";KeyValuePairstring, string> kvp2 = new KeyValuePairstring, string>();kvp2.Key = "IT";kvp2.Value = "Information Technology";
Try it

Generic Class Characteristics

A generic class increases the reusability. The more type parameters mean more reusable it becomes. However, too much generalization makes code difficult to understand and maintain. A generic class can be a base class to other generic or non-generic classes or abstract classes. A generic class can be derived from other generic or non-generic interfaces, classes, or abstract classes.

Generic Fields

A generic class can include generic fields. However, it cannot be initialized.

Example: Generic Field

class DataStore public T data;
The following declares a generic array.

Xem thêm: Số Bội Giác Là Gì ? Số Bội Giác Của Kính Lúp BộI Giác CủA Kính Lúp

Example: Generic Array

class DataStoreT> public T<> data = new T<10>;

Generic Methods

A method declared with the type parameters for its return type or parameters is called a generic method.

Example: Generic Methods

class DataStore{ private T<> _data = new T<10>; public void AddOrUpdate(int index, T item) if(index >= 0 &và index public T GetData(int index) if(index >= 0 && index return _data; else return default(T);
Above, the AddorUpdate() & the GetData() methods are generic methods. The actual data type of the thành phầm parameter will be specified at the time of instantiating the DataStore class, as shown below.

Example: Generic Methods

DataStorestring> cities = new DataStorestring>();cities.AddOrUpdate(0, "Mumbai");cities.AddOrUpdate(1, "Chicago");cities.AddOrUpdate(2, "London");DataStoreint> empIds = new DataStoreint>();empIds.AddOrUpdate(0, 50);empIds.AddOrUpdate(1, 65);empIds.AddOrUpdate(2, 89);
Try it
The generic parameter type can be used with multiple parameters with or without non-generic parameters và return type. The followings are valid generic method overloading.

Example: Generic Method Overloading

public void AddOrUpdate(int index, T data) public void AddOrUpdate(T data1, T data2) public void AddOrUpdate(T data1, U data2) public void AddOrUpdate(T data)
A non-generic class can include generic methods by specifying a type parameter in angle brackets with the method name, as shown below.

Xem thêm: Tâm Của Tam Giác Đều Là Gì, Định Nghĩa, Tính Chất Về Tam Giác Đều Chi Tiết

Example: Generic Method in Non-generic Class

class Printer public void Print(T data) Console.WriteLine(data); Printer printer = new Printer();printer.Printint>(100);printer.Print(200); // type infer from the specified valueprinter.Printstring>("Hello");printer.Print("World!"); // type infer from the specified value
Try it

Advantages of Generics

Generics increase the reusability of the code. You don"t need to lớn write code to lớn handle different data types. Generics are type-safe. You get compile-time errors if you try lớn use a different data type than the one specified in the definition. Generic has a performance advantage because it removes the possibilities of boxing và unboxing.
Learn C# using coding questions with answers & explanations.

C# Questions và Answers

Want khổng lồ kiểm tra how much you know C#?

Start C# Skill Test
Related Articles
Next is optimized for learning web technologies step by step. Examples might be simplified lớn improve reading & basic understanding. While using this site, you agree khổng lồ have read and accepted our terms of use and privacy policy.

E-mail list

Subscribe lớn gmail các mục và get lademo updates, tips & tricks on C#, .Net, JavaScript, jQuery, AngularJS, Node.js khổng lồ your inbox.

Chuyên mục: Ý NGHĨA
Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *