Skip to Main Content
C# 2008 Programmer's Reference
book

C# 2008 Programmer's Reference

by Wei-Meng Lee
November 2008
Intermediate to advanced content levelIntermediate to advanced
838 pages
16h 26m
English
Wrox
Content preview from C# 2008 Programmer's Reference

Chapter 9. Generics

One of the new features in the .NET Framework (beginning with version 2.0) is the support of generics in Microsoft Intermediate Language (MSIL). Generics use type parameters, which allow you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Generics enable developers to define type-safe data structures, without binding to specific fixed data types at design time.

Generics are a feature of the IL and not specific to C# alone, so languages such as C# and VB.NET can take advantage of them.

This chapter discusses the basics of generics and how you can use them to enhance efficiency and type safety in your applications. Specifically, you will learn:

  • Advantages of using generics

  • How to specify constraints in a generic type

  • Generic interfaces, structs, methods, operators, and delegates

  • The various classes in the .NET Framework class library that support generics

Understanding Generics

Let's look at an example to see how generics work. Suppose that you need to implement your own custom stack class. A stack is a last-in, first-out (LIFO) data structure that enables you to push items into and pop items out of the stack. One possible implementation is:

public class MyStack
{
    private int[] _elements;
    private int _pointer;

    public MyStack(int size)
    {
        _elements = new int[size];
_pointer = 0; } public void Push(int item) { if (_pointer > _elements.Length - 1) { throw new Exception("Stack ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 5.0 Programmer's Reference

C# 5.0 Programmer's Reference

Rod Stephens
Learning C# 2005, 2nd Edition

Learning C# 2005, 2nd Edition

Jesse Liberty, Brian MacDonald
A Programmer's Guide to C# 5.0, 4th Edition

A Programmer's Guide to C# 5.0, 4th Edition

Eric Gunnerson, Nick Wienholt
Beginning C# 6.0 Programming with Visual Studio 2015

Beginning C# 6.0 Programming with Visual Studio 2015

Benjamin Perkins, Jacob Vibe Hammer, Jon D. Reid

Publisher Resources

ISBN: 9780470285817Purchase book