471,337 Members | 1,036 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,337 software developers and data experts.

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 1632

"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:uE**************@TK2MSFTNGP10.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**************@TK2MSFTNGP10.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**************@TK2MSFTNGP10.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**************@TK2MSFTNGP10.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****************@TK2MSFTNGP15.phx.gbl...
Fernando Cacciola wrote:
Daniel O'Connell [C# MVP] wrote:
"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:uE**************@TK2MSFTNGP10.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 JALGenericCollection<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 JALGenericCollection(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
ObjectDisposedException("JALGenericCollection"); }
list.Add(d);
}
}
else { throw new ArgumentException(); }
}
public void Clear()
{
lock (syncLock)
{
if (disposed) { throw
new ObjectDisposedException("JALGenericCollection");
}
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 ObjectDisposedException("JALGenericCollection");
}
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 DisposeManagedResources()
{
lock (syncLock)
{
foreach (IDisposable d in list)
{
d.Dispose();
}
}
}
protected override void DisposeUnmanagedResources()
{
// 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.SayHello();
}
public int GetValue()
{
return pimplI2.GetValue();
}
}

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**************@TK2MSFTNGP10.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***@nickhounsome.me.uk> escribió en el mensaje
news:s_*********************@fe3.news.blueyonder.c o.uk...
"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:uE**************@TK2MSFTNGP10.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

"Jeff Louie" <je********@yahoo.com> escribió en el mensaje
news:%2***************@TK2MSFTNGP12.phx.gbl...
Sure.... 1) Write reusable code to that takes only objects of SomeType
that
also implements IDisposable.
Yes, right. As Nick also pointed out you fundamental advantage is that you
can specify more on one type in the constraint (which you can't with a
single non-generic paramter type)
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.


This example though is a bad one IMO.
You are explicitely forwarding the methods you know T1 and T2 have
(SayHello() and GetValue()), so there nothing
generic about them... a bare non-generic interface would do the same.
--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/
Feb 3 '06 #11
>
"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP15.phx.gbl...
Fernando Cacciola wrote:
Daniel O'Connell [C# MVP] wrote:
"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:uE**************@TK2MSFTNGP10.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.


So you think is common not to reply in inference and bind the method to a
type explicitely?
Do you have real world examples of that?
It was simply an example that can improve code quality if used probably. I disagree it improves code quality. Can you explain how and why?
I find I rarely use generic methods. Have you tried generic *types* at all
yet?
Do you mean generic structs and class?? Of course I did!
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.

How do you ensure you get back the type you expect exactly??
[and in your example there is no return type at all]

You need to pass the type _the calling functions_ wants.
Constriants (or interfaces in non-generic methods) let you do that exactly.
Again methods aren't all that interesting unless they *RETURN* the generic
type.
Really ??
Generic methods with a non-generic return type is pretty uninteresting.


What about Predicate<>?
Best

Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/
Feb 3 '06 #12
>

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.


What!!

Care to actually try it??

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

Feb 3 '06 #13

"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:OH*************@TK2MSFTNGP15.phx.gbl...

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.


What!!

Care to actually try it??


You are both introducing errors (I'm sure more in haste than ignorance):

List<string> list = new List(); // error - should be new List<string>()

list = Foo(list); // error - cannot assign IList to List<string>

Fernando - Explain to me how you are going to "modify list in some way" when
you don't know what it contains!

Consider:

class IInteresting { int ImpressMe(); }
class X : IInteresting {...}
int Foo<T>(IList<T> l) where T:IInteresting
{
return l[4].ImpressMe();
}

List<X> l = new List<X>();
Foo(l);

You cannot do this without a generic method.
Even "int Foo(IList<IInteresting> l)" wont do it because IList<X> is not an
IList<IInteresting> even if X implements IInteresting.

So you see constraints give extra "depth" to your typing.

Feb 3 '06 #14
Nick Hounsome wrote:
"Fernando Cacciola" <fe***************@hotmail.com> wrote in message
news:OH*************@TK2MSFTNGP15.phx.gbl...

With your version of the code "list = Foo(list);" would fail
because list is of type List<string> not IList.

Ha OK, is the assignment from the return type what fails.
I was only looking at the _parameter_ all this time because in my original
question I was looking for differences between parameters, not return types.

But Now I see what Daniel meant all along. Is the fact that you can assign
to the "list" lvalue what makes the generic interesting in this case. And
yes, that's very powerfull idiom, being able to return an object of the same
_dynamic_ type as an _actual_ parameter rather than the type of a _formal_
parameter.

Apologizes to Daniel for the misunderstanding.

Fernando - Explain to me how you are going to "modify list in some
way" when you don't know what it contains!

Consider:

class IInteresting { int ImpressMe(); }
class X : IInteresting {...}
int Foo<T>(IList<T> l) where T:IInteresting
{
return l[4].ImpressMe();
}

Ha, this is different than Daniel's example. It is not IList<T> itself the
generic parameter.
And yes, you cannot do this with interfaces.
So summarizing the responses:

(1) You can have more than one constriant.

(2) You can return a value with the actual type of a parameter instead of
its formal type.

(3) You can constaint the generic parameter of a generic argument (and not
just the generic argument itself), which provides type safesty at a deeper
level.

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


Feb 3 '06 #15
Fernando... Not really. The generic approach uses containment by
ownership at construction. The interface approach uses containment by
reference at construction. There is no guarantee that there is no other
reference to the contained object at construction. The interface method
provides a weak guarantee as opposed to the generic method strong
guarantee. There are however advantages to the interface approach since
you can pass parameters to the concrete class constructor.

Regards,
Jeff
a bare non-generic interface would do the same.<

*** Sent via Developersdex http://www.developersdex.com ***
Feb 3 '06 #16
Hi Jeff,
Fernando... Not really. The generic approach uses containment by
ownership at construction. The interface approach uses containment by
reference at construction. There is no guarantee that there is no
other reference to the contained object at construction. The
interface method provides a weak guarantee as opposed to the generic
method strong guarantee. There are however advantages to the
interface approach since you can pass parameters to the concrete
class constructor.

Ha well, yes, you're _constructing_ the types in the generic case.
Of course you could do the same with interfaces and factories but granted,
the generic version is a lot cleaner.

BTW, you can still pass parameters to the concrete class constructor using
the generic approach. Just as you forward each function in the proxy, you
can forward the constructor too.

Best
--
Fernando Cacciola
SciSoft
http://fcacciola.50webs.com/
Feb 3 '06 #17
This may work for a simple Foo(object o), but the interface approach
works for
any unforseen concrete class constructor as in new GenericClass(new
Foo(p1,
p2, p3, p4, p5)); as long as Foo is of the proper type IMyInterface.

Regards,
Jeff
BTW, you can still pass parameters to the concrete class constructor

using
the generic approach. Just as you forward each function in the proxy,
you
can forward the constructor too.<

*** Sent via Developersdex http://www.developersdex.com ***
Feb 3 '06 #18
Jeff Louie wrote:
This may work for a simple Foo(object o), but the interface approach
works for
any unforseen concrete class constructor as in new GenericClass(new
Foo(p1,
p2, p3, p4, p5)); as long as Foo is of the proper type IMyInterface.

But in your example you knew the exact signatures of each forwared method
(including parameters).
So, following that same logic, you should also know the exact signatures of
each constructor, thus you can list all necesary parameters (with their
correct types) in the GenericClass ctor.

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

Feb 3 '06 #19
Again i am going to argue not really. An interface describes the method
signatures, but not the signatures of the constructors, so an interface
does
not limit the set of allowable constructors. The generic class only
knows that
the type is a class, implements a specific interface and has a specific
set of
constructors. In the sample I posted the only supported constructor is
the no
arg constructor. The generic class does not know the details of all
concrete
classes present and _future_ of type T1 or T2 and therefore it cannot
know all
possible parameterized constructors of _future_ concrete classes of type
T1
or T2. Remember, the idea of using generics to simulate multiple
inheritance
of implementation is to support plugging in _new_ concrete classes with
new
implementations in the future without changing the calling code. These
new
classes may have new constructors with a different set of parameters
than
those present at the time of the writing of the generic class.

The interfaced based class has no such limitation as you can create a
new
class as in new Foo(new T1Implementation(p1,p2));

One possible solution is a generic constructor of form Foo(object[]
arrayParameters), but this is not type safe.

Regards,
Jeff
So, following that same logic, you should also know the exact

signatures of
each constructor, thus you can list all necesary parameters (with their
correct types) in the GenericClass ctor<

*** Sent via Developersdex http://www.developersdex.com ***
Feb 3 '06 #20

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

27 posts views Thread by Bernardo Heynemann | last post: by
4 posts views Thread by Tom Jastrzebski | last post: by
4 posts views Thread by Gazarsgo | last post: by
9 posts views Thread by sloan | last post: by
7 posts views Thread by JCauble | last post: by
7 posts views Thread by Andy Bell | last post: by
reply views Thread by rosydwin | last post: by

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.