Unlocking the Power of Generics - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Unlocking the Power of Generics

Description:

No loss of performance or code bloat. The .NET CLR recognizes Generics ... Code Bloat? Pros and Cons for each. Create Your Own Generics ... – PowerPoint PPT presentation

Number of Views:64
Avg rating:3.0/5.0
Slides: 28
Provided by: mattg64
Category:

less

Transcript and Presenter's Notes

Title: Unlocking the Power of Generics


1
Unlocking the Power of Generics
  • Matt Goebel
  • Crowe Chizek
  • CNUG February 15, 2006

2
Agenda
  • Traditional Collections and Drawbacks
  • Introduction to Generics
  • Value of Generics
  • Syntax and Samples

3
Traditional Collections
  • System.Collection namespace introduced in 1.0
    version of .NET Framework
  • Useful container types
  • Lists
  • Dictionaries
  • Hashtables
  • CollectionBase

4
Sample Class Definition
  • class Book
  • private int bookNumber 0
  • public int BookNumber
  • get return this.bookNumber
  • set this. bookNumber value
  • public Book( int _bookNumber )
  • this.bookNumber _bookNumber

5
Sample ArrayList Use
  • ArrayList bookList new ArrayList()
  • for( int i 0 i lt 20 i)
  • bookList.Add( new Book(i) )
  • IEnumerator listEnum bookList.GetEnumerator()
  • while( listEnum.MoveNext() )
  • Console.WriteLine(0,
  • ((Book)(listEnum.Current)).BookNumber)

6
Drawbacks
  • No type checking enforcement at compile time
  • Doesnt prevent adding unwanted types
  • Can lead to difficult to troubleshoot issues
  • Runtime errors!
  • All items are stored as objects
  • Must be cast going in and coming out
  • Performance overhead of boxing and unboxing
    specific types

7
Enforcing Consistent Types
  • Can control and eliminate unwanted types
  • Create wrapper class for each type

8
Enforcing Consistent Types
  • private class BookCollection CollectionBase
  • public Book this int index
  • get return (Book) Listindex
  • set Listindex value
  • public int Add( Book.BookNumber )
  • return List.Add(BookNumber)
  • public void Remove( Book.BookNumber )
  • List.Remove( BookNumber )

9
Enforcing Consistent Types
  • BookCollection bookCol new BookCollection ()
  • for( int i 0 i lt 20 i)
  • bookCol.Add( new Book(i) )
  • IEnumerator listEnum bookCol.GetEnumerator()
  • while( listEnum.MoveNext() )
  • Console.WriteLine(0,
  • ((Book)(listEnum.Current)).BookNumber)

10
Drawbacks
  • Previous example demonstrated enforcing
    consistent type use with 1.x
  • Code generators such as CodeSmith can generate
    wrappers for you
  • Larger code base even if it is by a code
    generator
  • Still has performance overhead of boxing and
    unboxing

11
The Generic Solution
  • Open constructed types
  • Classes defined without a specific type
  • Type is specified when instantiated
  • System.Collections.Generic namespace
  • List array dynamically sized as needed
  • Linked list doubly linked list
  • Queue first in, first out collection of objects
  • Stack last in, first out collection of objects

12
The Generic Solution Continued
  • Provides type safety at compile time
  • No loss of performance or code bloat
  • The .NET CLR recognizes Generics
  • Only one definition of a parameterized data
    structure, no matter how many types are used
  • Affects Microsoft Intermediate Language (MSIL)

13
VB.NET Generics Sample 1
  • Dim testCol As New List(Of int32)()
  • For i as int32 0 To 19
  • testCol.Add(i)
  • Next
  • For each someInt As int32 in testCol
  • Console.WriteLine(0, someInt)
  • Next

14
C Generics Sample 1
  • ArrayListltintgt testCol new ArrayListltintgt()
  • for (int i 0 i lt 20 i)
  • testCol.Add(i)
  • foreach (int someInt in testCol)
  • Console.WriteLine(0, someInt)

15
VB.NET Generics Sample 2
  • Dim bookList As New List(Of Book)()
  • For i as int32 0 To 19
  • bookList.Add(New Book(i))
  • Next
  • For each book As Book in bookList
  • Console.WriteLine(0, book.BookNumber)
  • Next

16
C Generics Sample 2
  • ArrayListltBookgt bookList new ArrayListltBookgt()
  • for (int i 0 i lt 20 i)
  • bookList.Add( new Book(i) )
  • foreach (Book book in bookList)
  • Console.WriteLine(0, book.BookNumber)

17
C Templates?
  • Generics are NOT equal to Templates
  • Compile-Time vs. Run-Time
  • Templates Compile-Time
  • Generics Run-Time
  • Code Bloat?
  • Pros and Cons for each

18
Create Your Own Generics
  • Generics can be applied a number of ways
  • Classes
  • Public Class MyType(Of T, U)
  • public class MyTypeltT,Ugt
  • Method return types and parameters
  • Public Function Foo() As T
  • public T Foo()
  • Fields and properties
  • Indexers, properties, events, structs,
    interfaces, etc.

19
Example of Create Your Own Generic
  • public class MyGenericltTgt
  • private static int objectCount 0
  • public MyGeneric()
  • objectCount
  • public int Count
  • get return objectCount
  • public T SomeMethod()

20
Example of Create Your Own Generic
  • Class SomeApplication
  • static void Main(string args)
  • MyGenericltintgt myIntGeneric new
    MyGenericltintgt()
  • MyGenericltintgt myIntGeneric2 new
    MyGenericltintgt()
  • int someInt myIntGeneric.SomeMethod()
  • MyGenericltBookgt myBookGeneric new
    MyGenericltBookgt()
  • Book someBook myBookGeneric.SomeMethod()
  • Console.WriteLine(myIntGeneric.Count)
  • Console.WriteLine(myIntGeneric2.Count)
  • Console.WriteLine(myBookGeneric.Count)
  • Console.WriteLine(new MyGenericltBookgt().Count)

2
2
1
2
21
Generic Methods
  • Can overload generic methods
  • Method signatures can be a challenge
  • Type parameters influence signature
  • Return type does not influence signature
  • Examples
  • Public ListltIgt FooltI, Jgt(I val1, ListltJgt val2)
  • Public void FooltK, Lgt(K val1, ListltLgt val2)

22
Constraints
  • Can apply constraints to limit the types used for
    the type parameter
  • Public Class MyClass(Of T As IMyClassA,
    IMyClassB)
  • End Class
  • Public class MyClassltTgt where T IMyClassA,
    IMyClassB

23
Default Values
  • Assign a default value when the type is not known
    until implementation
  • Assigns null for reference types
  • Assigns appropriate default value for built-in
    types
  • Only available in C for now
  • public class MyClass ltK, Vgt
  • public V Lookup(K key)
  • V retVal default(V)
  • return retVal

24
Nullable Types
  • Built-in data types such as int dont offer a
    good way to check if it has been assigned a value
  • System.NullableltTgt offers a nullable type
  • Nullableltintgt intVal null
  • if (!intVal.HasValue)
  • Console.WriteLine("Is null")
  • intVal 0
  • if (intVal.HasValue)
  • Console.WriteLine("Has value")

25
Power Collections
  • Open source library of generics
    http//www.wintellect.com/powercollections
  • Microsoft support and participation
  • Additional useful types
  • BigList
  • Deque
  • OrderedDictionary
  • OrderedSet
  • And more

26
More Information
  • An Introduction to C Generics
    -http//msdn.microsoft.com/library/default.asp?url
    /library/en-us/dnvs05/html/csharp_generics.asp
  • Generics in .NET Type Safety, Performance and
    Generality -http//www.codeguru.com/columns/dotne
    t/article.php/c9661/
  • Power Collections - http//www.wintellect.com/powe
    rcollections/
  • Generics in .NET 2.0 - http//www.ondotnet.com/p
    ub/a/dotnet/2005/06/20/generics.html

27
Need a Job?
  • Were Hiring Full Time Employees that have .NET
    development skills
  • Contact Tara Rodts
  • trodts_at_crowechizek.com
Write a Comment
User Comments (0)
About PowerShow.com