473,657 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics help

I am trying to create a parametrized generic object, but the compiler won't
let me. Is this just the way it is? The class has a constraint that says
all classes must inherit from BusinessBase, which specifies a parametrized
constructor. But c# won't let me do it.

public class DataHelper<Twhe re T : BusinessBase, new()
{
public static List<TDataTable ToList(DataTabl e dataTable)
{
List<TlistOfIte ms = new List<T>();

foreach (DataRow dr in dataTable.Rows)
{
T recipient = new T(dr); // **** causes an error ****
listOfItems.Add (recipient);
}

return listOfItems;
}
}
Nov 16 '07 #1
6 3278
The "new()" constraint specifies a public *parameterless* constructor,
so it won't know about T(dr).

The most pragmatic approach in this case would be to add a
ReadFromRow(Dat aRow) method to BusinessBase (perhaps abstract, if I
understand the intent), then you could use:

T recipient = new T();
recipient.ReadF romRow(DataRow) ;
listOfItems.Add (recipient);

This won't help if the properties are immutable and need to be set in
the ctor. You can use reflection to invoke a specific ctor, but it
loses all compile-time checking. Of course, what you are doing is
essentially a projection; so a Converter<DataR ow,Tmight be handy,
then you could do

foreach(DataRow dr in dataTable.Rows) {
listOfItems.Add (converter(dr)) ;
}

Finally, in C# 3 there is LINQ projection support on data-tables, so
something akin to (not tested):

var x = (from row in dataTable.AsEnu merable()
select new Person(row)).To List();

When the code is this simple, it is tempting to lose the helper method
- it also means that the projection ("select") can be very focused on
the task in hand - i.e. it could use an object-initializer instead, if
needed:

var x = (from row in dataTable.AsEnu merable()
select new Person(row.Fiel d<string>("Key" )) {
Name = row.Field<strin g>("Name"),
DateOfBirth = row.Field<DateT ime>("DOB")
}).ToList();
Marc
Nov 16 '07 #2
Hi Frank,

Currently only parameterless or default constructor is allowed as
constructor constraint on the class type.

#.NET: More on Generics in the CLR -- MSDN Magazine, October 2003
http://msdn.microsoft.com/msdnmag/issues/03/10/NET/
<quote>
The constructor constraint makes it possible for generic code to create
instances of the type specified by a type parameter by constraining type
arguments to types that implement a public default constructor. At this
time, only default or parameterless constructors are supported with the
constructor constraint.
</quote>

#Constraints on Type Parameters (C#)
http://msdn2.microsoft.com/en-us/lib...70(VS.80).aspx
<quote>
where T : new()
The type argument must have a public parameterless constructor.
</quote>

#where (C#)
http://msdn2.microsoft.com/en-us/lib...e8(VS.80).aspx
<quote>
The new() Constraint lets the compiler know that any type argument supplied
must have an accessible parameterless--or default-- constructor.
</quote>
You could either create a method to pass in the parameters or use
reflection to instantiate the type.
Regards,
Walter Wang (wa****@online. microsoft.com, remove 'online.')
Microsoft Online Community Support

=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====

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

Nov 16 '07 #3
Hi Frank,

Of course, C# 3.0 and LINQ really open up some nice possibilities here for
what you are trying to do. But if you don't have LINQ at your disposal and
you're confined to C# 2.0, I have a few suggestions that may help.

First, for the line that won't compile. One of the best ways to get around
this is to externalize the creation of your T type by using a generic
delegate that returns a T and accepts a DataRow. The downside to this is
that for each concrete type that T could be, you need to create a method
that can create one of those concrete types from a DataRow and then wire the
method up to an instance of your generic delegate. Then you make that
delegate instance available to the DataTableToList () method so it can use it
to do the work you need in the line that won't compile. In C# 2.0, you can
simplify this syntax a bit by using anonymous methods, or not, depending on
your preference.

Additionally, I would recommend that you not actually return a List<Tfrom
DataTableToList () but rather an IEnumerable<Tin stead. Then, you can turn
your DataTableToList () method into an iterator by using a yield block. This
lazy evaluation could gain you some efficiency if one were to only iterate
through the first few items of the list because you would only be calling
the delegate mentioned in the previous paragraph for the actual items
requested rather than for the whole DataTable.

Hope this helps,

-Trey

--
-----------------------------
Trey Nash
Author of "Accelerate d C# 2008" and "Accelerate d C# 2005"
Apress
"Frank Rizzo" <no**@none.comw rote in message
news:eI******** ******@TK2MSFTN GP02.phx.gbl...
>I am trying to create a parametrized generic object, but the compiler won't
let me. Is this just the way it is? The class has a constraint that says
all classes must inherit from BusinessBase, which specifies a parametrized
constructor. But c# won't let me do it.

public class DataHelper<Twhe re T : BusinessBase, new()
{
public static List<TDataTable ToList(DataTabl e dataTable)
{
List<TlistOfIte ms = new List<T>();

foreach (DataRow dr in dataTable.Rows)
{
T recipient = new T(dr); // **** causes an error
****
listOfItems.Add (recipient);
}

return listOfItems;
}
}
Nov 16 '07 #4
C# 3 there is LINQ projection support on data-tables
Oops; I meant .NET 3.5; subtle but important difference
row.Field<strin g>("Name"),
For info, this was just because my sample had an untyped DataTable; if
you have a typed DataTable, then you can:
a: lose the AsEnumerable()
b: access the properties directly

I also agree with the other poster's comment about return
IEnumerable<T- this allows the simple

var x = from row in typedDataTable
select new Person(row.Key) { Name = row.Name, DateOfBirth =
row.DOB};

(or the equivalent using the Select(...) method)

Marc
Nov 16 '07 #5
Frank Rizzo wrote:
I am trying to create a parametrized generic object, but the compiler won't
let me. Is this just the way it is? The class has a constraint that says
all classes must inherit from BusinessBase, which specifies a parametrized
constructor. But c# won't let me do it.

public class DataHelper<Twhe re T : BusinessBase, new()
{
public static List<TDataTable ToList(DataTabl e dataTable)
{
List<TlistOfIte ms = new List<T>();

foreach (DataRow dr in dataTable.Rows)
{
T recipient = new T(dr); // **** causes an error ****
listOfItems.Add (recipient);
}

return listOfItems;
}
}


I think you can use a litter trick to solve (if this way don't break
your classes desgin)
public class DataHelper<Twhe re T : BusinessBase, new()
{
public static List<TDataTable ToList(DataTabl e
dataTable,Fetch ObjectDelegate< TfetchObject)
{
List<TlistOfIte ms = new List<T>();

foreach (DataRow dr in dataTable.Rows)
{
T recipient = fetchObject(dr) ; // delegate create
object task to another method
listOfItems.Add (recipient);
}

return listOfItems;
}
}
And you just make new delegate for each business object.

public delegate T FetchObjectDele gate<T>(DataRow dr);

public static class FetchObjectMeth ods {
public static Company FetchCompany(Da taRow dr) {
return new Company(dr);
}
public static Employee FetchCompany(Da taRow dr) {
return new Employee (dr);
}
}
Nov 16 '07 #6
For info, that is identical to the Converter<DataR ow,Tapproach I
already cited, except that Converter<DataR ow, Tuses a well-known
delegate.

Marc
Nov 16 '07 #7

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

Similar topics

9
3024
by: Chuck Bowling | last post by:
I assume that 2.0 will be rolled out with VS.NET 2004. Does anybody know if MS is planning to ship an STL package with it?
17
3316
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even impossible to write truly generic code. For example, it seems to be impossible to write a truly generic
5
1285
by: J.Marsch | last post by:
All: I have an interesting problem in front of me. does this sound reasonable, or ridiculous? I have to build something that is sort of like a style sheet for Windows controls. Picture a collection of dissimilar value types: a couple of Color types, some ints, some strings etc.
7
3498
by: Gene Vital | last post by:
Hi all, I need some help in understanding how to use Generics. I have a class based on a user control that can be put on any Container at runtime, I want to be able to call a method on the parent class without knowing the type of the parent class, can this be done with C#? I thought this was what Generics was supposed to be all about but I have spent the whole day Googling and I can't find a way to do this in C#.
23
2539
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
12
2734
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
1556
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 :)
9
5971
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. ...
18
2630
by: riftimes | last post by:
Hello, would you help me to find totorials with examples about generics and Dictionary thank you.
4
1938
by: Random | last post by:
I want to define a generics method so the user can determine what type they expect returned from the method. By examining the generics argument, I would determine the operation that needs to be performed and do just that. However, out of the two possible ways of doing this, neither seems to work. I thought I could either... 1) overload the method just based on the generics argument Public Function GetData (Of T As SqlDataReader)...
0
8403
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
8833
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...
1
8509
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
8610
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7345
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
4168
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
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2735
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
1967
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.