Generic c# là gì


Generic means the general form, not specific. In C#, generic means not specific lớn a particular data type.

C# allows you lớn define generic classes, interfaces, abstract classes, fields,methods, static methods, properties, events, delegates, & operators using the type parameter and 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, 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, và delegates in the DataStore class. For example, Data is generic property because we have sầu used a type parameter T as its type instead of the specific data type.

chú ý It is not required to use T as a type parameter. You can give sầu any name to lớn a type parameter. Generally, T is used when there is only one type parameter. It is recommended to use a more readable type parameter name as per requirement like 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.quý khách sẽ 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.

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


You can assign a string value lớn the Data property. Trying 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 ADVERTISEMENT

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 lớn understvà & maintain. A generic class can be a base class lớn 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 Example: Generic Array

class DataStoreT> public T data = new T;

Generic Methods

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

Xem thêm: Ipo Là Gì? Cách Mua Cổ Phiếu Ipo ? Cách Đăng Ký Mua Cổ Phiếu Ipo Ở Nhật

Example: Generic Methods

class DataStore{ private T _data = new T; public void AddOrUpdate(int index, T item) if(index >= 0 && index public T GetData(int index) if(index >= 0 && index return _data; else return default(T); Above sầu, the AddorUpdate() and the GetData() methods are generic methods. The actual data type of the cống 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 & 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: " Down The Line Là Gì ? Down The Line Có Nghĩa Là Gì

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 lớn write code lớn handle different data types. Generics are type-safe. You get compile-time errors if you try to 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 and explanations.

C# Questions và Answers

Want to kiểm tra how much you know C#?

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

TutorialsE-mail menu

Subscribe to gmail danh mục & get lademo updates, tips & tricks on C#, .Net, JavaScript, jQuery, AngularJS, Node.js to lớn your inbox.