Generics in C#

原创 2004年10月11日 18:30:00

Generics in C#

Generics are the most useful C# 2.0 language extensions, beside Anonymous methods, Iterators, Partial types And Nullable types.

What are generics?
Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate.

Why generics?
To well know the useful of generics lets examine the following code:--
 
public class Stack
{
object[] items;
int count;
public void Push(object item) {...}
public object Pop() {...}
}

We use the object type to store any type of data. The above simple Stack class stores its data in an object array, and its two methods, Push and Pop, use object to accept and return data. While the use of type object makes the Stack class very flexible, it is not without drawbacks. For example, it is possible to push a value of any type, such a Customer instance, onto a stack.

However, when a value is retrieved, the result of the Pop method must explicitly be cast back to the appropriate type, which is tedious to write and carries a performance penalty for run-time type checking:
 
Stack stack = new Stack();
stack.Push(new Customer());
Customer c = (Customer)stack.Pop();

If a value of a value type, such as an int, is passed to the Push method, it is automatically boxed. When the int is later retrieved, it must be unboxed with an explicit type cast:

Stack stack = new Stack();
stack.Push(3);
int i = (int)stack.Pop();

Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.

A further issue with the Stack class is that it is not possible to enforce the kind of data placed on a stack. Indeed, a Customer instance can be pushed on a stack and then accidentally cast it to the wrong type after it is retrieved:

Stack stack = new Stack();
stack.Push(new Customer());
string s = (string)stack.Pop();

While the code above is an improper use of the Stack class, the code is technically speaking correct and a compile-time error is not reported. The problem does not become apparent until the code is executed, at which point an InvalidCastException is thrown.

With generics those problems are all solved. HOW ??

public class Stack<T>
{
T[] items;
int count;
public void Push(T item) {...}
public T Pop() {...}
}

When the generic class Stack<T> is used, the actual type to substitute for T is specified. In the following example, int is given as the type argument for T:

Stack<int> stack = new Stack<int>();
stack.Push(3);
int x = stack.Pop();

generics.jpg

The Stack<int> type is called a constructed type. In the Stack<int> type, every occurrence of T is replaced with the type argument int. When an instance of Stack<int> is created, the native storage of the items array is an int[] rather than object[], providing substantial storage efficiency compared to the non-generic Stack. Likewise, the Push and Pop methods of a Stack<int> operate on int values, making it a compile-time error to push values of other types onto the stack, and eliminating the need to explicitly cast values back to their original type when theye retrieved.

Generics provide strong typing, meaning for example that it is an error to push an int onto a stack of Customer objects. Just as a Stack<int> is restricted to operate only on int values, so is Stack<Customer> restricted to Customer objects, and the compiler will report errors on the last two lines of the following example:

Stack<Customer> stack = new Stack<Customer>();
stack.Push(new Customer());
Customer c = stack.Pop();
stack.Push(3); // Type mismatch error
int x = stack.Pop(); // Type mismatch error

It was a breif introduction to generics that will be included in the next version of C# (V 2.0) . which is available now on its beta version with Visual C# 2005 Express Edition Beta 1.

C#中的Generics

C#中竟然也加入了Generics功能,微软,真不知让我说什么好了。
  • zhangweis
  • zhangweis
  • 2004年09月09日 14:53
  • 746

c#2.0新特性:(一)泛型(Generics)

为了提高应用程序的效率和可用性,C#2.0引入了泛型概念.C#泛型有些类似C++的摸版。(一)特点        泛型具有以下功能特点:     一、使用泛型可以定义类型安全的数据结构,而无需使用实际...
  • zhouhuan965
  • zhouhuan965
  • 2012年12月27日 16:19
  • 640

C# - Generics

Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generic...
  • chimomo
  • chimomo
  • 2014年11月17日 10:38
  • 1322

Java学习(1)-Java.Generics

  Generics1) Introduction引言 1.1)为什么需要泛型?Generics add stability to your code by making more of your b...
  • budapest
  • budapest
  • 2007年07月04日 09:43
  • 3005

《Java Generics and Collections》读书笔记二:子类化与通配符

参考资料: 《Java Generics and Collections》1. 子类型与替换原则ListNumber> 是 CollectionNumber> 的子类型, 但 ListInteger>...
  • kjndppl
  • kjndppl
  • 2008年01月09日 23:12
  • 347

Java泛型(Generics)

参考:http://docs.oracle.com/javase/tutorial/java/generics/index.html 为什么要使用泛型
  • navyhu
  • navyhu
  • 2014年10月28日 10:53
  • 2433

Generics are not supported at this language level

选择File---->Project Structure  修改Project language level为7
  • genghaihua
  • genghaihua
  • 2015年11月23日 10:31
  • 4498

Java的generics跟C++的template有何区别?

讨论来自stackoverflow 详细解释大家看原文,只翻译结论 Java代码里出现的尖括弧看上去很像C++的template,但其实正式名字叫generics,它不像C++模板(一个加强版...
  • happen23
  • happen23
  • 2016年03月10日 10:48
  • 360

Generics in C#

IntroductionSome New features have been added to C# language with version 2.0 of .NET. which are: Ge...
  • waterboy
  • waterboy
  • 2004年08月24日 20:13
  • 676

Java基础学习——泛型(generics)学习一

概述在JDK 5.0,Java语言引入了好几个新的功能,其中很重要的一个就是泛型(generics)。本文就是对泛型的概述,简单定义以及子类型的介绍。本文翻译自Java官网教程。...
  • shuanghujushi
  • shuanghujushi
  • 2016年08月01日 20:19
  • 476
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Generics in C#
举报原因:
原因补充:

(最多只允许输入30个字)