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

Home Posts Topics Members FAQ

Problems with generics

I have come across a problem using generics. I want to create a Factory type
that will build classes for me. Code snippet below...

static public class Product<T> where T : new()
{
static public T New()
{
return new T();
}
}

public class Factory<T> : List<Product<T> >
{
public Factory()
{
}

public List<T> BuildAll()
{
List<T> result = new List<T>();

foreach (T item in this)
{
result.Add(Prod uct<T>.New());
}

return result;
}
}

The problem lies in that the Factory's type <T> requires the new constraint
(like Factory), but that will conflict with the base class descriptor.

I know that I can imbed the List<> (ala Decorator pattern), but I would hope
there is another way to solve it.

--
Thanks,
Nov 16 '05 #1
8 1843
Leicester B. Ford Jr. wrote:
I have come across a problem using generics. I want to create a Factory type
that will build classes for me. Code snippet below...

static public class Product<T> where T : new()


What means "static class" for C# 2.0? Probably you cannot instantiate
that class because it's static.

bye
Rob
Nov 16 '05 #2
You can't instantiate a static class, and I am not doing that. I am
instantiating the type that is passed to the class (the class is there for
the New method).

The problem is that I am passing the type to the Builder class, and I need
that type to be "newable" where you add a constraint ": new()", but since the
Builder class is also decended from the List class, there is no syntax to
also define the incoming meta type as a newable class.

"Robert Jordan" wrote:
Leicester B. Ford Jr. wrote:
I have come across a problem using generics. I want to create a Factory type
that will build classes for me. Code snippet below...

static public class Product<T> where T : new()


What means "static class" for C# 2.0? Probably you cannot instantiate
that class because it's static.

bye
Rob

Nov 16 '05 #3
This doesn't look correct to me - a Factory is not a kind of List. Your
underlying problem from a design point of view is that you're trying to turn
a List into something that it's not. Is there some reason that Factory can't
just aggregate an instance of List as a field?
--
Mickey Williams
Author, "Visual C# .NET Core Ref", MS Press
www.neudesic.com
www.servergeek.com
"Leicester B. Ford Jr." <Le*******@onli ne.nospam> wrote in message
news:D1******** *************** ***********@mic rosoft.com...
I have come across a problem using generics. I want to create a Factory
type
that will build classes for me. Code snippet below...

static public class Product<T> where T : new()
{
static public T New()
{
return new T();
}
}

public class Factory<T> : List<Product<T> >
{
public Factory()
{
}

public List<T> BuildAll()
{
List<T> result = new List<T>();

foreach (T item in this)
{
result.Add(Prod uct<T>.New());
}

return result;
}
}

The problem lies in that the Factory's type <T> requires the new
constraint
(like Factory), but that will conflict with the base class descriptor.

I know that I can imbed the List<> (ala Decorator pattern), but I would
hope
there is another way to solve it.

--
Thanks,

Nov 16 '05 #4
My question suggested that I could:

....I know that I can imbed the List<> (ala Decorator pattern), but I would
hope there is another way to solve it...

I might have referenced the wrong pattern (I sometimes get them confused),
but you get the point.

What I was concerned about was that the syntax for declaring a constraint on
a generic type could only be used if the class that the generic type was
defined on, did not have an ancestor class.

Along those lines, you are not able to define a constraint on a method:

public void MyMethod<t : new()>() // wrong
public void MyMethod<t>:new ()() // wrong

The only way to define the constraint at this point is to define it on the
encapsulting class... which leads me back to my question.

Oh, BTW, Why can't a factory be a kind of a list? You could fill it up with
all of the types you want to create, and mass produce them in one call. Or
you could specify the specific types that you want to create, and raise an
error if you are trying to create a type not in the Factory's list.

But generally, I agree that you would probably create multiple instances of
the factory, one for each type of Product.

Thanks,

"Mickey Williams [C# MVP]" wrote:
This doesn't look correct to me - a Factory is not a kind of List. Your
underlying problem from a design point of view is that you're trying to turn
a List into something that it's not. Is there some reason that Factory can't
just aggregate an instance of List as a field?
--
Mickey Williams
Author, "Visual C# .NET Core Ref", MS Press
www.neudesic.com
www.servergeek.com
"Leicester B. Ford Jr." <Le*******@onli ne.nospam> wrote in message
news:D1******** *************** ***********@mic rosoft.com...
I have come across a problem using generics. I want to create a Factory
type
that will build classes for me. Code snippet below...

static public class Product<T> where T : new()
{
static public T New()
{
return new T();
}
}

public class Factory<T> : List<Product<T> >
{
public Factory()
{
}

public List<T> BuildAll()
{
List<T> result = new List<T>();

foreach (T item in this)
{
result.Add(Prod uct<T>.New());
}

return result;
}
}

The problem lies in that the Factory's type <T> requires the new
constraint
(like Factory), but that will conflict with the base class descriptor.

I know that I can imbed the List<> (ala Decorator pattern), but I would
hope
there is another way to solve it.

--
Thanks,


Nov 16 '05 #5

"Leicester B. Ford Jr." <Le*******@onli ne.nospam> wrote in message
news:98******** *************** ***********@mic rosoft.com...
Oh, BTW, Why can't a factory be a kind of a list? You could fill it up
with
all of the types you want to create, and mass produce them in one call.


Then you should pass those parameters to the create method. The factory just
isn't a container for other objects supporting sequential iteration.
--
Mickey Williams
Author, "Visual C# .NET Core Ref", MS Press
www.neudesic.com
www.servergeek.com
Nov 16 '05 #6

"Leicester B. Ford Jr." <Le*******@onli ne.nospam> wrote in message
news:98******** *************** ***********@mic rosoft.com...
...I know that I can imbed the List<> (ala Decorator pattern), but I would
hope there is another way to solve it...
Sorry, missed that. My bad.
What I was concerned about was that the syntax for declaring a constraint
on
a generic type could only be used if the class that the generic type was
defined on, did not have an ancestor class.
That's correct.

Along those lines, you are not able to define a constraint on a method:


Right - the constraint is a type thing.
--
Mickey Williams
Author, "Visual C# .NET Core Ref", MS Press
www.neudesic.com
www.servergeek.com
Nov 16 '05 #7
Thanks for your response,

My example may not be the sterling example of the limitation of generics,
but I believe the point to be valid.

Concerning Factory lists... I think it is just a matter of style.

Consider a class (not Factory), that encompasses a list. The arguments for
making that class a decendant, vs making the list internal, are the same as
could be argued for a Factory class. AFAIK, there is nothing special about a
Factory (as in design pattern), that indicates it should not be a list.

If your point is that by superclassing the List, it basically merges the
functionality of a List, and a Factory, making the class more complex to
understand. I have no disagreement with this.

BTW, the solution of passing things in the constructor works only at
instatiation, but doesn't allow the consumer of the object to modify the list
subsiquently, unless the list is exposed publicly. You can assume that I did
not mean for the list to be static or unreachable (by the consumer), since I
explictly designed it not to be.

P.S. This structure was presented to describe a point, not really to argue
"best practice". It was the first thing that I thought of where the class
name could help document the problem... I wanted a Factory that could (new)
build generic Products, and that Factory had to be descended from *something*
that was itself generic.

"Mickey Williams [C# MVP]" wrote:

"Leicester B. Ford Jr." <Le*******@onli ne.nospam> wrote in message
news:98******** *************** ***********@mic rosoft.com...
Oh, BTW, Why can't a factory be a kind of a list? You could fill it up
with
all of the types you want to create, and mass produce them in one call.


Then you should pass those parameters to the create method. The factory just
isn't a container for other objects supporting sequential iteration.
--
Mickey Williams
Author, "Visual C# .NET Core Ref", MS Press
www.neudesic.com
www.servergeek.com

Nov 16 '05 #8
Sorry I haven't responded sooner... It seems that email responses are not
sent, unless you click on the link EVERY time.

Thanks for your response.

I didn't know that there was a different group for Whidbey (VS2005), I will
repost my question where you suggest.

"Kevin Yu [MSFT]" wrote:
Hi Leicester,

If I understand your problem correctly, you're going to use Generics to
write a Factory class to build products. This is beyond the scope of the
newgroup, since this group is mainly discussing about the released .net
frameworks. It would be best handle by the Microsoft Visual Studio 2005
Newsgroups group. For a quicker response you may want to try reposting the
question in the following link:

http://communities.microsoft.com/new...idbey&slcid=us

Unfortunately the Visual Studio 2005 Newsgroups are not part of the managed
newsgroup list that we guarantee a 2 business day response, so the response
from the community could take a little bit longer. For a list MSDN Managed
newsgroups please visit the following link;

http://msdn.microsoft.com/newsgroups/managed/

Thanks!

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #9

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

Similar topics

11
4001
by: andrew queisser | last post by:
I've read some material on the upcoming Generics for C#. I've seen two types of syntax used for constraints: - direct specification of the interface in the angle brackets - where clauses I looked at the files in the Gyro download but I couldn't find any mention of constraints. Can anyone enlighten me what the current status is and what we can expect when Generics are released? Thanks,
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.
5
2921
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have an "AppleBasket" which is a class that contains a collection of apples. So, some code: class Fruit{ }
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
8
2433
by: Kris Jennings | last post by:
Hi, I am trying to create a new generic class and am having trouble casting a generic type to a specific type. For example, public class MyClass<Twhere T : MyItemClass, new() { public MyClass() { } public void AppendItem()
8
3189
by: mark.norgate | last post by:
I've run into a few problems trying to use generics for user controls (classes derived from UserControl). I'm using the Web Application model rather than the Web Site model. The first problem I'm having is that the partial class signature in my projectDetails.ascx.cs file looks like this: public partial class ProjectDetailsControl<TEntryServiceProvider: UserControl, INamingContainer where TEntryServiceProvider : IEntryServiceProvider...
7
2214
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
13
3837
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
3
2729
by: =?Utf-8?B?RnJhbmsgVXJheQ==?= | last post by:
Hi all I have some problems with Crystal Reports (Version 10.2, Runtime 2.0). In Section3 I have added a OLE Object (Bitmap). Now when I open the report in my code I would like to set this OLE Object (load a picture from a given path). Something like this I would expect: _reports.crImage local_Report = new _reports.crImage();
3
1301
by: Anders Borum | last post by:
Hello, I've worked on an API for quite some time and have (on several occasions) tried to introduce generics at the core abstract level of business objects (especially a hierarchical node). The current non-generic implementation is functional, but not as clean as I would like. Although not sure, I believe my problems stem from lacking support of co- and contravariance in C# (which I'm desperately hoping will make it in the next version)....
0
9589
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
9423
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
10216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
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...
0
8873
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...
0
6675
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
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
3565
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.