473,769 Members | 2,382 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What are Constrained Generics good for??

I'm puzzled,

Why and how _exactly_ is this:

void Foo<T>(T v ) where T : Interface/Value/Class/class

any better than this

void Foo( Interface/Value/Class/object v )

??

Are generics ANY useful for anything but to avoid boxing??

TIA
--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/

Feb 2 '06 #1
19 1772

"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...
I'm puzzled,

Why and how _exactly_ is this:

void Foo<T>(T v ) where T : Interface/Value/Class/class

any better than this

void Foo( Interface/Value/Class/object v )

??

Are generics ANY useful for anything but to avoid boxing??


It offers a better face and a higher probability of correctness, simply put.
In your above example, you would be constrainted to explicitly what you
use(that is, any object implementing Interface is valid). When using
constrained generics the method will only accept the type you provide it
with:

Given: public void Foo<T>(T t) where T : IEnumerable

then:

List<string> list;
Array array;
Foo<List<string >>(list); //acceptable
Foo<List<string >>(array); //fails

Although Array does implement IEnumerable, its not acceptable because it is
not of type List. It is a minor value, certainly, but a value none hte less.

Personally I find generic methods to be far more useful when they use the
generic in the return value.

Given: public T Foo<T>(T v) where T : IList
{
//modify list in some way
}

List<string> list = new List();
//... populate list somehow
list = Foo(list);

It eliminates casts and ensures the type returned is the type you expect and
not just a random type that supports IList.

Generics on a class level help significantly in maintaining a constant
interface and having a consistent type instead of just a type with a distant
common base.
Feb 2 '06 #2
Daniel O'Connell [C# MVP] wrote:
"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...
I'm puzzled,

Why and how _exactly_ is this:

void Foo<T>(T v ) where T : Interface/Value/Class/class

any better than this

void Foo( Interface/Value/Class/object v )

??

Are generics ANY useful for anything but to avoid boxing??

It offers a better face and a higher probability of correctness,
simply put. In your above example, you would be constrainted to
explicitly what you use(that is, any object implementing Interface is
valid). When using constrained generics the method will only accept
the type you provide it with:

Given: public void Foo<T>(T t) where T : IEnumerable

then:

List<string> list;
Array array;
Foo<List<string >>(list); //acceptable
Foo<List<string >>(array); //fails

Although Array does implement IEnumerable, its not acceptable because
it is not of type List.


I don't get that...
If the constriant is that T must support IEnumerable, why can't I pass an
Array?
Are you sure?

Personally I find generic methods to be far more useful when they use
the generic in the return value.

Given: public T Foo<T>(T v) where T : IList
{
//modify list in some way
}

List<string> list = new List();
//... populate list somehow
list = Foo(list);
I can do the exact same thing with:

public IList Foo(IList v)
{
//modify list in some way
}

I can't see ANY difference.
Generics on a class level help significantly in maintaining a constant
interface and having a consistent type instead of just a type with a
distant common base.


I don't get it.
Maybe I'm missing something about how constriants work?

TIA
--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/
Feb 2 '06 #3
Fernando Cacciola wrote:
Daniel O'Connell [C# MVP] wrote:
"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...
I'm puzzled,

Why and how _exactly_ is this:

void Foo<T>(T v ) where T : Interface/Value/Class/class

any better than this

void Foo( Interface/Value/Class/object v )

??

Are generics ANY useful for anything but to avoid boxing??


It offers a better face and a higher probability of correctness,
simply put. In your above example, you would be constrainted to
explicitly what you use(that is, any object implementing Interface is
valid). When using constrained generics the method will only accept
the type you provide it with:

Given: public void Foo<T>(T t) where T : IEnumerable

then:

List<string> list;
Array array;
Foo<List<string >>(list); //acceptable
Foo<List<string >>(array); //fails

Although Array does implement IEnumerable, its not acceptable because
it is not of type List.


I don't get that...
If the constriant is that T must support IEnumerable, why can't I
pass an Array?
Are you sure?

Personally I find generic methods to be far more useful when they use
the generic in the return value.

Given: public T Foo<T>(T v) where T : IList
{
//modify list in some way
}

List<string> list = new List();
//... populate list somehow
list = Foo(list);

I can do the exact same thing with:

public IList Foo(IList v)
{
//modify list in some way
}

I can't see ANY difference.
Generics on a class level help significantly in maintaining a
constant interface and having a consistent type instead of just a
type with a distant common base.


I don't get it.
Maybe I'm missing something about how constriants work?

TIA

Feb 2 '06 #4
Fernando Cacciola wrote:
Daniel O'Connell [C# MVP] wrote:
"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...

[SNIPPED

Given: public void Foo<T>(T t) where T : IEnumerable

then:

List<string> list;
Array array;
Foo<List<string >>(list); //acceptable
Foo<List<string >>(array); //fails
I don't get that...
If the constriant is that T must support IEnumerable, why can't I
pass an Array?


Ha well, I just noticed you specifically passed List<string> as the template
argument for the second Foo call.
Well, normally you won't supply the type to a generic function (that's what
type inference is for).
Unless you meant to say that since you _can_ explicitely bind the generic
method to a type instead of relying on type inference, you add _some degree_
of type safesty.
I'm not sure I buy that: if Foo is declared to accept IEnumerable, why would
it be a mistake to call it with ANY type implementing that? Constraints are
precisely there to specify the semantics of the acceptable types; to
restrict even further on the caller side is a mistake IMHO.

--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/
Feb 2 '06 #5

"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:%2******** ********@TK2MSF TNGP15.phx.gbl. ..
Fernando Cacciola wrote:
Daniel O'Connell [C# MVP] wrote:
"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...

[SNIPPED

Given: public void Foo<T>(T t) where T : IEnumerable

then:

List<string> list;
Array array;
Foo<List<string >>(list); //acceptable
Foo<List<string >>(array); //fails
I don't get that...
If the constriant is that T must support IEnumerable, why can't I
pass an Array?


Ha well, I just noticed you specifically passed List<string> as the
template argument for the second Foo call.
Well, normally you won't supply the type to a generic function (that's
what type inference is for).
Unless you meant to say that since you _can_ explicitely bind the generic
method to a type instead of relying on type inference, you add _some
degree_ of type safesty.


Type inference applies only to generic methods, which is far from their only
use. It was simply an example that can improve code quality if used
probably. I find I rarely use generic methods. Have you tried generic
*types* at all yet?
I'm not sure I buy that: if Foo is declared to accept IEnumerable, why
would it be a mistake to call it with ANY type implementing that?
Constraints are precisely there to specify the semantics of the acceptable
types; to restrict even further on the caller side is a mistake IMHO.

So you can insure you get back the type you expect or that you pass in the
type you want. Again methods aren't all that interesting unless they
*RETURN* the generic type. Generic methods with a non-generic return type is
pretty uninteresting.
Feb 2 '06 #6

Personally I find generic methods to be far more useful when they use
the generic in the return value.

Given: public T Foo<T>(T v) where T : IList
{
//modify list in some way
}

List<string> list = new List();
//... populate list somehow
list = Foo(list);
I can do the exact same thing with:

public IList Foo(IList v)
{
//modify list in some way
}

I can't see ANY difference.

No, you can't.

With your version of the code "list = Foo(list);" would fail because list is
of type List<string> not IList. The return value is what matters there.
You'd have to cast the return value back to the type you are using.
Generics on a class level help significantly in maintaining a constant
interface and having a consistent type instead of just a type with a
distant common base.
I don't get it.
Maybe I'm missing something about how constriants work?

Constraints declare a set of interfaces, base types, and perhaps a
parameterless constructor that must be there. Note that is it both more
flexible than a single interface(you can't declare a parameter that must be
both IEnumerable and IComparable, for example) and clearer because you see
an absolute type, not just an interface. That is a litlte harder to find on
generic methods however. It shines a bit more on generic classes.

TIA
--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/

Feb 2 '06 #7
Sure.... 1) Write reusable code to that takes only objects of SomeType
that
also implements IDisposable. The code should call Dispose on all
contained
objects when you call Dispose on the container. The container shall only
contain objects of SomeType.

// generic collection
public class JALGenericColle ction<T,R,P> : Disposable, IInvoke<R,P>
where T : IDisposable, IInvoke<R,P>
{
private readonly object syncLock = new object();
private List<T> list = new List<T>();
private R r = default(R);
public JALGenericColle ction(R r)
{
this.r = r;
}
// ASSERT d is not null
// ASSERT no object holds a reference to
// d outside of this class
// USAGE Add(new MyClass()); ** newed reference idiom **
// where MyClass implements IDisposable and IInvoke
public void Add(T d)
{
if (d != null)
{
lock (syncLock)
{
if (disposed) { throw
new
ObjectDisposedE xception("JALGe nericCollection "); }
list.Add(d);
}
}
else { throw new ArgumentExcepti on(); }
}
public void Clear()
{
lock (syncLock)
{
if (disposed) { throw
new ObjectDisposedE xception("JALGe nericCollection ");
}
foreach (IDisposable d in list)
{
d.Dispose();
}
list.Clear();
}
}

public R Invoke(P p)
{
R r = default(R);
// no one can add or delete during this critical section
lock (syncLock)
{
if (disposed) { throw
new ObjectDisposedE xception("JALGe nericCollection ");
}
foreach (IInvoke<R,P> i in list)
{
r= i.Invoke(p);
//if (this.r == r) break; // == on generic types NOT
ALLOWED!
}
}
return r;
}
protected override void DisposeManagedR esources()
{
lock (syncLock)
{
foreach (IDisposable d in list)
{
d.Dispose();
}
}
}
protected override void DisposeUnmanage dResources()
{
// do nothing
}
}

2) Write code that simulates multiple inheritance of implementation so
that
you can plug in any set of concrete classes into the code that
implements the
set of interfaces of the class.

// finally we write the generic class that contains
// the concrete classes
public class GenericMI<T1, T2> : IProgram where T1 : class, I1,
new()
where T2: class,I2, new()
{
private T1 pimplI1= new T1();
private T2 pimplI2 = new T2();
// we forward calls to the contained object
public void SayHello()
{
pimplI1.SayHell o();
}
public int GetValue()
{
return pimplI2.GetValu e();
}
}

Regards,
Jeff
Are generics ANY useful for anything but to avoid boxing??<


*** Sent via Developersdex http://www.developersdex.com ***
Feb 3 '06 #8
"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...
I'm puzzled,

Why and how _exactly_ is this:

void Foo<T>(T v ) where T : Interface/Value/Class/class

any better than this

void Foo( Interface/Value/Class/object v )

??

Are generics ANY useful for anything but to avoid boxing??


Their main use is to avoid runtime casting exceptions - Compile time errors
are better than runtime ones.

You can also express more powerful interface restrictions with constraints
than you can with parameter types - Constraints can restrict a parameter to
implement 2 or more unrelated interfaces whereas a parameter type can only
restrict to 1.
Feb 3 '06 #9

"Nick Hounsome" <nh***@nickhoun some.me.uk> escribió en el mensaje
news:s_******** *************@f e3.news.blueyon der.co.uk...
"Fernando Cacciola" <fe************ ***@hotmail.com > wrote in message
news:uE******** ******@TK2MSFTN GP10.phx.gbl...
I'm puzzled,

Why and how _exactly_ is this:

void Foo<T>(T v ) where T : Interface/Value/Class/class

any better than this

void Foo( Interface/Value/Class/object v )

??

Are generics ANY useful for anything but to avoid boxing??

Their main use is to avoid runtime casting exceptions -
Just like non-generic interfaces (or base types).
Compile time errors are better than runtime ones.
Exactly like those you get using interfaces or base types.
You can also express more powerful interface restrictions with constraints
than you can with parameter types
- Constraints can restrict a parameter to implement 2 or more unrelated
interfaces whereas a parameter type can only restrict to 1.

Now THIS is a good point (the only good point I've seen so far).

Thank you.
--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/

Feb 3 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
2462
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and still no can do... Any info would be great!
7
1255
by: Leicester B. Ford Jr. | last post by:
I have this class: public class ItemType .... public class ProductType<T> where T: ItemType .... Now I want to add an IDisposable interface to ProductType...
4
391
by: Tom Jastrzebski | last post by:
Hello everybody, Here is the problem I came across experimenting with Generics. I would like to write a class or a struct adding integer to any other, initially undefined *numeric type*. So, my struct would look more or less like: struct MySum<T> where T : struct { public static T AddInteger(T value, int i) { return value + i;
12
2744
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as it defines the language more completely. Great to use.
4
1560
by: Gazarsgo | last post by:
This seems to be a bit of a contradiction, but how can I construct a Generic class using a System.Type variable that is assigned at run time? Is there some parallel to the Generics concept that extends to having strictly-typed classes at run-time? I would gladly give up the compile-time errors if I could get rid of all these CType()s :)
11
2501
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes provide an implemation of the operator +. Now I want to write another generic class Plan<DType>, which can
9
5986
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
7
2098
by: JCauble | last post by:
I have a question about using Generics with Interfaces and some of there inheritance issues / problems. If this is not possible what I describe below I will have to go a different route and would like some suggestions. I am unable to use abstract classes as my code must not effect any current inheritance chains so I am using interfaces. So I have something like this: interface IBase { Collection<IBaseItemItems{get;set;}
7
1292
by: Andy Bell | last post by:
Can this be done via .net generics? How? The % signs below are just to show how I want to do it, I realise they're not valid syntax. public abstract class BaseSelectionRequirement { ... protected Type mControlType; protected string mFieldName; protected Type mFieldType; protected UserControl mControl; ...
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.