SlideShare ist ein Scribd-Unternehmen logo
1 von 30
GENERICS
Sasha Goldshtein
blog.sashag.net | @goldshtn
What Is This Talk?
• Understanding how generics are implemented in
  C++, Java and .NET at the runtime and machine-code
  level
• Understanding the performance implications and other
  pros/cons of each mechanism

• We will not learn how to use generics
Why Do We Want Them?
• “Pure” object-oriented programming does not always
  provide a clean and type-safe solution with good
  performance
• In other words, what’s wrong here?


  public class ArrayList {
    object[] items;
    public void Add(object item) { ... }
    public object ElementAt(int index) { ... }
  }
The C++ Approach
         “Templates, the smart macros from hell.”

• Use parameterized template as a sketch
• No constraints on the original template code
• Everything happens at compile-time


    template <typename RanIt>
    void sort(RanIt begin, RanIt end) {
      … if (*begin < *(begin+1)) …
    }
C++ Template Definition
template <typename T>
class vector {
  T* data; int size; int cap;
public:
  vector(int capacity) { ... }
  void push_back(const T& datum) { ... }
  T operator[](int index) const { ... }
};
C++ Template Instantiation
You say:
vector<int> v(2);



Compiler says:
class __vector__int__ {
  int* data; int size; int cap;
public:
  vector(int capacity) { ... }
};
C++ Template Instantiation
You say:
vector<int> v(2);
v.push_back(42);

Compiler says:
class __vector__int__ {
  int* data; int size; int cap;
public:
  vector(int capacity) { ... }
  void push_back(const int& datum) { ... }
};
C++ Template Instantiation
You say:
vector<EmptyClass> v(2);
sort(v.begin(), v.end());

Compiler says:
error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const
std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const
std::vector<_Ty,_Alloc> &' from 'EmptyClass'
  vector(1724) : see declaration of 'std::operator <'
  templatesstuff.cpp(20) : see reference to function template instantiation
  'void sort<std::_Vector_iterator<_Myvec>>(RanIt,RanIt)' being compiled
    with
    [
      _Myvec=std::_Vector_val<std::_Simple_types<EmptyClass>>,
      RanIt=std::_Vector_iterator<std::_Vector_val<
             std::_Simple_types<EmptyClass>>>
    ]
The C++ Approach—Pros and Cons
          Pros                       Cons

• No performance cost      • Can’t share templates
• Very flexible              between translation
• Full compile-time type     units
  safety                   • Can’t share templates
                             between libraries (code
                             bloat)
                           • Can’t reliably export
                             templates from libraries
                           • No constraints = no
                             readable compiler
                             errors
The Java Approach
• Use parameterized template as a compiler aid
• Constraints used to prove things to the compiler
• Erase type information at runtime


    public class LinkedList<E> {
      private LinkedList<E> head;
      private E value;
      public void add(E element) { ... }
      public E getAt(int index) { ... }
    }
Java Generic Type Erasure
There is just one type (raw type) at runtime:

public class LinkedList {
  private LinkedList head;
  private Object value;
  public void add(Object element) { ... }
  public Object getAt(int index) { ... }
}
Java Generic Type Constraints
Cannot use anything but java.lang.Object methods
without specifying constraint (wildcard):

public class SortedList<E
  extends Comparable<E>> {
  ...
  public void add(E element) {
    ... if (element.compareTo(other)) ...
  }
}
The Java Approach—Pros and Cons
         Pros                       Cons

• Backwards compatible    • Can’t use generics with
  with non-generic Java     primitive types
  versions                • Can’t distinguish
• Constraint violation      between generic class
  results in clear          instantiations
  compiler error          • Can’t instantiate
• Can share generic         generic type
  types and objects         parameters (“new E”)
  between                 • Can’t use type
  packages/applications     parameters in static
                            methods or fields
The .NET Approach
• Use parameterized template as a compiler aid and a
  runtime code generation sketch for the JIT
• Constraints used to prove things to the compiler


    public class List<T> {
      T[] items; int size; int cap;
      public void Add(T item) { ... }
      public T this[int index] {
        get { ... } set { ... }
      }
    }
Digression: .NET Object Layout
.NET Generic Types at Runtime
• There is a separate type at runtime for each generic
  instantiation, but not necessarily a separate copy of the
  methods’ code
• Does this method’s machine code depend on T?


    public void Add(T item) {
      if (size < items.Length – 1) {
        items[size] = item;
        ++size;
      } else AllocateAndAddSlow(item);
    }
.NET Generic Code Sharing
Concrete Example: Stack Push
BasicStack`1[[System.__Canon, mscorlib]].Push(System.__Canon)
00260360 57              push    edi
00260361 56              push    esi
00260362 8b7104          mov     esi,dword ptr [ecx+4]
00260365 8b7908          mov     edi,dword ptr [ecx+8]
00260368 8d4701          lea     eax,[edi+1]
0026036b 894108          mov     dword ptr [ecx+8],eax
0026036e 52              push    edx
0026036f 8bce            mov     ecx,esi
00260371 8bd7            mov     edx,edi
00260373 e8f4cb3870      call    clr!JIT_Stelem_Ref (705ecf6c)
00260378 5e              pop     esi
00260379 5f              pop     edi
0026037a c3              ret
Concrete Example: Stack Push
BasicStack`1[[System.Int32, mscorlib]].Push(Int32)
002603c0 57              push    edi
002603c1 56              push    esi
002603c2 8b7104          mov     esi,dword ptr [ecx+4]
002603c5 8b7908          mov     edi,dword ptr [ecx+8]
002603c8 8d4701          lea     eax,[edi+1]
002603cb 894108          mov     dword ptr [ecx+8],eax
002603ce 3b7e04          cmp     edi,dword ptr [esi+4]
002603d1 7307            jae     002603da
002603d3 8954be08        mov     dword ptr [esi+edi*4+8],edx
002603d7 5e              pop     esi
002603d8 5f              pop     edi
002603d9 c3              ret
002603da e877446170      call    clr!JIT_RngChkFail (70874856)
002603df cc              int     3
Concrete Example: Stack Push
BasicStack`1[[System.Double, mscorlib]].Push(Double)
00260420 56              push    esi
00260421 8b5104          mov     edx,dword ptr [ecx+4]
00260424 8b7108          mov     esi,dword ptr [ecx+8]
00260427 8d4601          lea     eax,[esi+1]
0026042a 894108          mov     dword ptr [ecx+8],eax
0026042d 3b7204          cmp     esi,dword ptr [edx+4]
00260430 730c            jae     0026043e
00260432 dd442408        fld     qword ptr [esp+8]
00260436 dd5cf208        fstp    qword ptr [edx+esi*8+8]
0026043a 5e              pop     esi
0026043b c20800          ret     8
0026043e e813446170      call    clr!JIT_RngChkFail (70874856)
00260443 cc              int     3
Type-Specific Code
• What about new T[12] or typeof(T).FullName?
• When .NET generic methods need access to T, they get it
 from the method table (this or hidden parameter)

• …Unless the type parameters are value types, in which
 case the MT is hard-coded into the method:
C#:
Foo<T>() { … typeof(T) … }            T=int
Machine code:
mov      ecx,offset 798b6844 (MT: System.Int32)
call     clr!JIT_GetRuntimeType (6ca40aa8)
Generics and Reflection
• Because generic types are first-class citizens, they are
 accessible to Reflection at runtime

  Type to = typeof(Dictionary<,>);
  Type tc = to.MakeGenericType(
                          typeof(string), typeof(int));

  to = typeof(List<double>).GetGenericTypeDefinition();
  tc = to.MakeGenericType(typeof(int)); //List<int>
Generic Constraints
• .NET constraints restrict type parameters at compile-
  time, very similar to Java’s
• Only a limited set of constraints available:
  • Interface constraint:   where   T   :   IComparable<T>
  • Base constraint:        where   T   :   UserControl
  • Category constraint:    where   T   :   class or where T : struct
  • Constructor constraint: where   T   :   new()


  Note that constraints don’t break the machine code equivalence
  for reference types. Why?
Case Study: IEquatable<T>
     public static void CallEquals<T>(T inst) {
       inst.Equals(inst);
     }

public struct Point {
  public int   X, Y;
  public override    bool Equals(object o) {
    if (o is Point) return Equals((Point)o);
    return false;
  }
  public bool Equals(Point pt) { ... }
}
Case Study: IEquatable<T>
• CallEquals has no constraints, so the C# compiler
  chooses the Object.Equals(Object) virtual method
• We can add an interface constraint with a strongly-typed
  Equals method—now the compiler prefers it
  • Note: the interface call has no virtual cost on value types


    public static void CallEquals<T>(T inst)
      where T : IEquatable<T>
    {
      inst.Equals(inst);
    }
Sorting “If Possible”, a la C++
public class List<T> {
  T[] items; ...
  public void Add(T item) { ... }
  public void Sort(SortProvider<T> sorter = null) {
    sorter = sorter ?? SortProvider<T>.GetDefault();
    if (sorter == null)
      throw new NotImplementedException();
    sorter.Sort(items);
  }
}
Sorting “If Possible”, a la C++
public abstract class SortProvider<T> {
  public abstract void Sort(T[] items);
  public static SortProvider<T> GetDefault() {
    if (T is IComparable<T>)
      return new DefaultSortProvider<T>();
    if (T is IGreaterthanable<T>)
      return new GreaterThanSortProvider<T>();
    return null;
  }
}
internal class DefaultSortProvider<T> : SortProvider<T>
  where T : IComparable<T> {
  //Use T.CompareTo for sorting
}
Getting Generic Math Right in .NET
• Pretty nasty:
• Consider Complex<T>: you can’t implement operators…
• Solution sketch:
  • Define ICalculator<T> with methods instead of operators
  • Implement ICalculator<T> for each T
  • Choose between ICalculator<T>’s implementations at
    runtime, and use them in your generic math code
  • For more:
   http://www.codeproject.com/Articles/8531/Using-generics-for-calculations
The .NET Approach—Pros and Cons

           Pros                          Cons

• Constraint violation        • Constraints are not
  results in clear compiler     enough for everything
  error                         (e.g., generic math)
• Can share generic types     • No meta-programming
  and objects between           abilities (advantage?)
  packages/applications
• Can use generics
  efficiently with value
  types
• Can use Reflection to
  query over generic types
QUESTIONS?
Sasha Goldshtein
blog.sashag.net | @goldshtn

Weitere ähnliche Inhalte

Was ist angesagt?

Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingHariz Mustafa
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharphmanjarawala
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language InnovationsShahriar Hyder
 

Was ist angesagt? (18)

Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Java generics final
Java generics finalJava generics final
Java generics final
 
C# p9
C# p9C# p9
C# p9
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Java Generics
Java GenericsJava Generics
Java Generics
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language Innovations
 

Andere mochten auch

9 subprograms
9 subprograms9 subprograms
9 subprogramsjigeno
 
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Leon Osinski
 
A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4Leon Osinski
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-onlyAshwin Kumar
 
Oracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOtto Paiz
 
16 logical programming
16 logical programming16 logical programming
16 logical programmingjigeno
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutionsAshwin Kumar
 
Software engineering lecture notes
Software engineering lecture notesSoftware engineering lecture notes
Software engineering lecture notesSiva Ayyakutti
 
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...TURKI , PMP
 
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless TechnologiesPresentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless TechnologiesKaushal Kaith
 

Andere mochten auch (19)

Oops
OopsOops
Oops
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
Generics C#
Generics C#Generics C#
Generics C#
 
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
Auteursrecht in academische omgeving: DPO Professionaliseringsbijeenkomst, 23...
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
 
Raspuns MS Subprogram FIV 2016
Raspuns MS Subprogram FIV 2016Raspuns MS Subprogram FIV 2016
Raspuns MS Subprogram FIV 2016
 
A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4A basic course on Research data management: part 1 - part 4
A basic course on Research data management: part 1 - part 4
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Oracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guideOracle database 12c sql worshop 1 activity guide
Oracle database 12c sql worshop 1 activity guide
 
16 logical programming
16 logical programming16 logical programming
16 logical programming
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
 
Csci360 08-subprograms
Csci360 08-subprogramsCsci360 08-subprograms
Csci360 08-subprograms
 
Software engineering lecture notes
Software engineering lecture notesSoftware engineering lecture notes
Software engineering lecture notes
 
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
Free PMP notes,Free PMP Study Material,Free PMP Chapter wise notes,PMP Exam N...
 
E-Commerce PPT
E-Commerce PPTE-Commerce PPT
E-Commerce PPT
 
E commerce
E commerceE commerce
E commerce
 
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless TechnologiesPresentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
Presentation on 1G/2G/3G/4G/5G/Cellular & Wireless Technologies
 

Ähnlich wie Generics in .NET, C++ and Java

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Java parallel programming made simple
Java parallel programming made simpleJava parallel programming made simple
Java parallel programming made simpleAteji Px
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 
Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Yulia Tsisyk
 
State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net PerformanceCUSTIS
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsStephane Gleizes
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Raimon Ràfols
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Featurestarun308
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And EnumsBhushan Mulmule
 

Ähnlich wie Generics in .NET, C++ and Java (20)

final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
02basics
02basics02basics
02basics
 
Java parallel programming made simple
Java parallel programming made simpleJava parallel programming made simple
Java parallel programming made simple
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"
 
State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net Performance
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Templates2
Templates2Templates2
Templates2
 
report
reportreport
report
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
 
C chap22
C chap22C chap22
C chap22
 

Mehr von Sasha Goldshtein

Modern Linux Tracing Landscape
Modern Linux Tracing LandscapeModern Linux Tracing Landscape
Modern Linux Tracing LandscapeSasha Goldshtein
 
The Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF PrimerThe Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF PrimerSasha Goldshtein
 
Staring into the eBPF Abyss
Staring into the eBPF AbyssStaring into the eBPF Abyss
Staring into the eBPF AbyssSasha Goldshtein
 
Visual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET FrameworkVisual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET FrameworkSasha Goldshtein
 
Swift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSwift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSasha Goldshtein
 
C# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with XamarinC# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with XamarinSasha Goldshtein
 
Modern Backends for Mobile Apps
Modern Backends for Mobile AppsModern Backends for Mobile Apps
Modern Backends for Mobile AppsSasha Goldshtein
 
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013Sasha Goldshtein
 
Mastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionMastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionSasha Goldshtein
 
Delivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in MinutesDelivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in MinutesSasha Goldshtein
 
Building Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET BackendBuilding Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET BackendSasha Goldshtein
 
Building iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile ServicesBuilding iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile ServicesSasha Goldshtein
 
Attacking Web Applications
Attacking Web ApplicationsAttacking Web Applications
Attacking Web ApplicationsSasha Goldshtein
 
Windows Azure Mobile Services
Windows Azure Mobile ServicesWindows Azure Mobile Services
Windows Azure Mobile ServicesSasha Goldshtein
 
First Steps in Android Development
First Steps in Android DevelopmentFirst Steps in Android Development
First Steps in Android DevelopmentSasha Goldshtein
 

Mehr von Sasha Goldshtein (20)

Modern Linux Tracing Landscape
Modern Linux Tracing LandscapeModern Linux Tracing Landscape
Modern Linux Tracing Landscape
 
The Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF PrimerThe Next Linux Superpower: eBPF Primer
The Next Linux Superpower: eBPF Primer
 
Staring into the eBPF Abyss
Staring into the eBPF AbyssStaring into the eBPF Abyss
Staring into the eBPF Abyss
 
Visual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET FrameworkVisual Studio 2015 and the Next .NET Framework
Visual Studio 2015 and the Next .NET Framework
 
Swift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSwift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS X
 
C# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with XamarinC# Everywhere: Cross-Platform Mobile Apps with Xamarin
C# Everywhere: Cross-Platform Mobile Apps with Xamarin
 
Modern Backends for Mobile Apps
Modern Backends for Mobile AppsModern Backends for Mobile Apps
Modern Backends for Mobile Apps
 
.NET Debugging Workshop
.NET Debugging Workshop.NET Debugging Workshop
.NET Debugging Workshop
 
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
Performance and Debugging with the Diagnostics Hub in Visual Studio 2013
 
Mastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and ProductionMastering IntelliTrace in Development and Production
Mastering IntelliTrace in Development and Production
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
 
State of the Platforms
State of the PlatformsState of the Platforms
State of the Platforms
 
Delivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in MinutesDelivering Millions of Push Notifications in Minutes
Delivering Millions of Push Notifications in Minutes
 
Building Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET BackendBuilding Mobile Apps with a Mobile Services .NET Backend
Building Mobile Apps with a Mobile Services .NET Backend
 
Building iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile ServicesBuilding iOS and Android Apps with Mobile Services
Building iOS and Android Apps with Mobile Services
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Attacking Web Applications
Attacking Web ApplicationsAttacking Web Applications
Attacking Web Applications
 
Windows Azure Mobile Services
Windows Azure Mobile ServicesWindows Azure Mobile Services
Windows Azure Mobile Services
 
First Steps in Android Development
First Steps in Android DevelopmentFirst Steps in Android Development
First Steps in Android Development
 

Kürzlich hochgeladen

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 

Generics in .NET, C++ and Java

  • 2. What Is This Talk? • Understanding how generics are implemented in C++, Java and .NET at the runtime and machine-code level • Understanding the performance implications and other pros/cons of each mechanism • We will not learn how to use generics
  • 3. Why Do We Want Them? • “Pure” object-oriented programming does not always provide a clean and type-safe solution with good performance • In other words, what’s wrong here? public class ArrayList { object[] items; public void Add(object item) { ... } public object ElementAt(int index) { ... } }
  • 4. The C++ Approach “Templates, the smart macros from hell.” • Use parameterized template as a sketch • No constraints on the original template code • Everything happens at compile-time template <typename RanIt> void sort(RanIt begin, RanIt end) { … if (*begin < *(begin+1)) … }
  • 5. C++ Template Definition template <typename T> class vector { T* data; int size; int cap; public: vector(int capacity) { ... } void push_back(const T& datum) { ... } T operator[](int index) const { ... } };
  • 6. C++ Template Instantiation You say: vector<int> v(2); Compiler says: class __vector__int__ { int* data; int size; int cap; public: vector(int capacity) { ... } };
  • 7. C++ Template Instantiation You say: vector<int> v(2); v.push_back(42); Compiler says: class __vector__int__ { int* data; int size; int cap; public: vector(int capacity) { ... } void push_back(const int& datum) { ... } };
  • 8. C++ Template Instantiation You say: vector<EmptyClass> v(2); sort(v.begin(), v.end()); Compiler says: error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'EmptyClass' vector(1724) : see declaration of 'std::operator <' templatesstuff.cpp(20) : see reference to function template instantiation 'void sort<std::_Vector_iterator<_Myvec>>(RanIt,RanIt)' being compiled with [ _Myvec=std::_Vector_val<std::_Simple_types<EmptyClass>>, RanIt=std::_Vector_iterator<std::_Vector_val< std::_Simple_types<EmptyClass>>> ]
  • 9. The C++ Approach—Pros and Cons Pros Cons • No performance cost • Can’t share templates • Very flexible between translation • Full compile-time type units safety • Can’t share templates between libraries (code bloat) • Can’t reliably export templates from libraries • No constraints = no readable compiler errors
  • 10. The Java Approach • Use parameterized template as a compiler aid • Constraints used to prove things to the compiler • Erase type information at runtime public class LinkedList<E> { private LinkedList<E> head; private E value; public void add(E element) { ... } public E getAt(int index) { ... } }
  • 11. Java Generic Type Erasure There is just one type (raw type) at runtime: public class LinkedList { private LinkedList head; private Object value; public void add(Object element) { ... } public Object getAt(int index) { ... } }
  • 12. Java Generic Type Constraints Cannot use anything but java.lang.Object methods without specifying constraint (wildcard): public class SortedList<E extends Comparable<E>> { ... public void add(E element) { ... if (element.compareTo(other)) ... } }
  • 13. The Java Approach—Pros and Cons Pros Cons • Backwards compatible • Can’t use generics with with non-generic Java primitive types versions • Can’t distinguish • Constraint violation between generic class results in clear instantiations compiler error • Can’t instantiate • Can share generic generic type types and objects parameters (“new E”) between • Can’t use type packages/applications parameters in static methods or fields
  • 14. The .NET Approach • Use parameterized template as a compiler aid and a runtime code generation sketch for the JIT • Constraints used to prove things to the compiler public class List<T> { T[] items; int size; int cap; public void Add(T item) { ... } public T this[int index] { get { ... } set { ... } } }
  • 16. .NET Generic Types at Runtime • There is a separate type at runtime for each generic instantiation, but not necessarily a separate copy of the methods’ code • Does this method’s machine code depend on T? public void Add(T item) { if (size < items.Length – 1) { items[size] = item; ++size; } else AllocateAndAddSlow(item); }
  • 17. .NET Generic Code Sharing
  • 18. Concrete Example: Stack Push BasicStack`1[[System.__Canon, mscorlib]].Push(System.__Canon) 00260360 57 push edi 00260361 56 push esi 00260362 8b7104 mov esi,dword ptr [ecx+4] 00260365 8b7908 mov edi,dword ptr [ecx+8] 00260368 8d4701 lea eax,[edi+1] 0026036b 894108 mov dword ptr [ecx+8],eax 0026036e 52 push edx 0026036f 8bce mov ecx,esi 00260371 8bd7 mov edx,edi 00260373 e8f4cb3870 call clr!JIT_Stelem_Ref (705ecf6c) 00260378 5e pop esi 00260379 5f pop edi 0026037a c3 ret
  • 19. Concrete Example: Stack Push BasicStack`1[[System.Int32, mscorlib]].Push(Int32) 002603c0 57 push edi 002603c1 56 push esi 002603c2 8b7104 mov esi,dword ptr [ecx+4] 002603c5 8b7908 mov edi,dword ptr [ecx+8] 002603c8 8d4701 lea eax,[edi+1] 002603cb 894108 mov dword ptr [ecx+8],eax 002603ce 3b7e04 cmp edi,dword ptr [esi+4] 002603d1 7307 jae 002603da 002603d3 8954be08 mov dword ptr [esi+edi*4+8],edx 002603d7 5e pop esi 002603d8 5f pop edi 002603d9 c3 ret 002603da e877446170 call clr!JIT_RngChkFail (70874856) 002603df cc int 3
  • 20. Concrete Example: Stack Push BasicStack`1[[System.Double, mscorlib]].Push(Double) 00260420 56 push esi 00260421 8b5104 mov edx,dword ptr [ecx+4] 00260424 8b7108 mov esi,dword ptr [ecx+8] 00260427 8d4601 lea eax,[esi+1] 0026042a 894108 mov dword ptr [ecx+8],eax 0026042d 3b7204 cmp esi,dword ptr [edx+4] 00260430 730c jae 0026043e 00260432 dd442408 fld qword ptr [esp+8] 00260436 dd5cf208 fstp qword ptr [edx+esi*8+8] 0026043a 5e pop esi 0026043b c20800 ret 8 0026043e e813446170 call clr!JIT_RngChkFail (70874856) 00260443 cc int 3
  • 21. Type-Specific Code • What about new T[12] or typeof(T).FullName? • When .NET generic methods need access to T, they get it from the method table (this or hidden parameter) • …Unless the type parameters are value types, in which case the MT is hard-coded into the method: C#: Foo<T>() { … typeof(T) … } T=int Machine code: mov ecx,offset 798b6844 (MT: System.Int32) call clr!JIT_GetRuntimeType (6ca40aa8)
  • 22. Generics and Reflection • Because generic types are first-class citizens, they are accessible to Reflection at runtime Type to = typeof(Dictionary<,>); Type tc = to.MakeGenericType( typeof(string), typeof(int)); to = typeof(List<double>).GetGenericTypeDefinition(); tc = to.MakeGenericType(typeof(int)); //List<int>
  • 23. Generic Constraints • .NET constraints restrict type parameters at compile- time, very similar to Java’s • Only a limited set of constraints available: • Interface constraint: where T : IComparable<T> • Base constraint: where T : UserControl • Category constraint: where T : class or where T : struct • Constructor constraint: where T : new() Note that constraints don’t break the machine code equivalence for reference types. Why?
  • 24. Case Study: IEquatable<T> public static void CallEquals<T>(T inst) { inst.Equals(inst); } public struct Point { public int X, Y; public override bool Equals(object o) { if (o is Point) return Equals((Point)o); return false; } public bool Equals(Point pt) { ... } }
  • 25. Case Study: IEquatable<T> • CallEquals has no constraints, so the C# compiler chooses the Object.Equals(Object) virtual method • We can add an interface constraint with a strongly-typed Equals method—now the compiler prefers it • Note: the interface call has no virtual cost on value types public static void CallEquals<T>(T inst) where T : IEquatable<T> { inst.Equals(inst); }
  • 26. Sorting “If Possible”, a la C++ public class List<T> { T[] items; ... public void Add(T item) { ... } public void Sort(SortProvider<T> sorter = null) { sorter = sorter ?? SortProvider<T>.GetDefault(); if (sorter == null) throw new NotImplementedException(); sorter.Sort(items); } }
  • 27. Sorting “If Possible”, a la C++ public abstract class SortProvider<T> { public abstract void Sort(T[] items); public static SortProvider<T> GetDefault() { if (T is IComparable<T>) return new DefaultSortProvider<T>(); if (T is IGreaterthanable<T>) return new GreaterThanSortProvider<T>(); return null; } } internal class DefaultSortProvider<T> : SortProvider<T> where T : IComparable<T> { //Use T.CompareTo for sorting }
  • 28. Getting Generic Math Right in .NET • Pretty nasty: • Consider Complex<T>: you can’t implement operators… • Solution sketch: • Define ICalculator<T> with methods instead of operators • Implement ICalculator<T> for each T • Choose between ICalculator<T>’s implementations at runtime, and use them in your generic math code • For more: http://www.codeproject.com/Articles/8531/Using-generics-for-calculations
  • 29. The .NET Approach—Pros and Cons Pros Cons • Constraint violation • Constraints are not results in clear compiler enough for everything error (e.g., generic math) • Can share generic types • No meta-programming and objects between abilities (advantage?) packages/applications • Can use generics efficiently with value types • Can use Reflection to query over generic types