Developer community
0 votes
1.5k views
asked by Expert (11.4k points) 14 22 29 | 1.5k views

1 Answer

0 votes
Well, it turns out that .NET generics have a major limitation - they requirethe type parameter to be constrained. For example, you cannot do this:
static class Disposer<T>
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The C# compiler will refuse to compile this code, as the type T has not been constrained, and therefore only supports the methods of System.Object. Dispose is not a method on System.Object, so the compilation fails. To fix this code, we need to add a where clause, to reassure the compiler that our type T does indeed have a Dispose method
static class Disposer<T> where T : IDisposable
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The problem is that the requirement for explicit contraints is very limiting. We can use constraints to say that T implements a particular interface, but we can't dilute that to simply say that T implements a particular method.
Contrast this with C++ templates (for example), where no constraint at all i required - it is assumed (and verified at compile time) that if the code Satish Marwat Dot Net Web Resources satishcm@gmail.com 32 Page invokes the Dispose() method on a type, then the type will support the method.
In fact, after writing generic code with interface constraints, we quickly see that we haven't gained much over non-generic interface-based programming. For example, we can easily rewrite the Disposer class without generics:
static class Disposer
{
public static void Dispose( IDisposable obj ) { obj.Dispose(); }
}
answered by Sr Member (5k points) 7 9 12

Related questions

0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 23 31 | 571 views
0 votes
1 answer
asked by smith Geek (15.3k points) 17 40 60 | 17 views
0 votes
1 answer
asked by omari Sr Member (3.9k points) 5 8 11 | 4 views
0 votes
1 answer
asked by felin Advisor (8.4k points) 10 15 18 | 35 views
0 votes
1 answer
asked by felin Advisor (8.4k points) 10 15 18 | 52 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users