473,781 Members | 2,280 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
19 1773

"Jeff Louie" <je********@yah oo.com> escribió en el mensaje
news:%2******** *******@TK2MSFT NGP12.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******** ********@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.


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******** *****@TK2MSFTNG P15.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<IInte resting> l)" wont do it because IList<X> is not an
IList<IInterest ing> 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******** *****@TK2MSFTNG P15.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 misunderstandin g.

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(ne w
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(ne w
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 T1Implementatio n(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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
2463
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
2099
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
9636
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...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10075
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,...
1
7485
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
5373
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
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.