Santiago,
Searching on Groups.google.com
Generic types are typesafe to the type they are bound to.
From the draft of the ECMA spec:
<quote>
No special conversions exist between constructed reference types other
than those described in §15. In particular, unlike array types,
constructed reference types do not exhibit "co-variant" conversions.
This means that a type List<B> has no conversion (either implicit or
explicit) to List<A> even if B is derived from A. Likewise, no
conversion exists from List<B> to List<object>.
[Note: The rationale for this is simple: if a conversion to List<A> is
permitted, then apparently, one can store values of type A into the
list. However, this would break the invariant that every object in a
list of type List<B> is always a value of type B, or else unexpected
failures can occur when assigning into collection classes. end note]
</quote>
So you're right - no casting between generics.
--
Dave Cline
www.davecline.com/
davecline@...
>Trying to cast an object to it's interface well, that would be like trying
to turn a person into a painting.
Dave, your anology is wrong. It's perfectly valid to cast an object to an
interface it supports. Inclusive you don't even need to explicitly cast it:
IMammal m3 = m2;
Only when going the other way around you need to cast:
Managers.Add((Manager)m3);
Santiago, the problem you're having is that Generics in C# are "invariants".
A List<Person> is completely unrelated with List<Manager>, although Manager
inherits from Person.
Maybe this blog post will help you:
http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx
If all you care is to have a list with the same elements, than you can just
create a new list and copy the original list in.
List<Person> persons = new List<Person>(Managers.ToArray());
Best Regards,
Paulo Carreiro
-----Original Message-----
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of santiago.perez@...
Sent: 05 June 2006 20:10
To: StrongTypes@yahoogroups.com
Subject: Re: [StrongTypes] Casting a SortedList Generic Class to a generic
Class of base type.
Hey Dave thanks for your help and insight into casting to an Interface. I
understand what you mean, and I follow your example to the T. My only
problem is that I want Cast a list of one type to it's base which youdidn't
have an example of, something like this:
List<Person> Persons =Managers ;
DO I need to specifically cast it as follows?:
List<Person> Persons =(List<Person>)Managers ;
NO matter what I try I can't cast a list of a sublass to it's base. This
doesn't seem like something that MS wouldn't have thought about.
Thanks again.
Santiago Perez
Florida's Turnpike Enterprise
Programmer Analyst
Pompano Operations
Ph 954-975-4855 ex 1127
Cell 954-444-9429
"Dave Cline"
<davecline@gmail.
com> To
Sent by: StrongTypes@yahoogroups.com
StrongTypes@yahoo cc
groups.com
Subject
Re: [StrongTypes] Casting a
06/04/2006 06:08 SortedList Generic Class to a
PM generic Class of base type.
Please respond to
StrongTypes@yahoo
groups.com
I'm not expert, in anybody's book, but I believe you're trying to use an
interface like a base class. An interface is really just a signature, a
template if you will. It does not represent inheritance. Trying to cast an
object to it's interface well, that would be like trying to turn a person
into a painting. It can't be done without breaking a few laws of nature not
to mention Newtonian physics. But you can turn a person into a child, or
senior citizen or mammal or vertebrate. A picture of a person is really just
a plan, a image of a three dimensional entity.
Try not using an interface as a generics type. Below was my testing rig.
But I maybe way off here.
DC
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfaceTesting
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Testing Inheritance");
Manager m1 = new Manager();
m1.Name = "Manager M1";
System.Console.WriteLine("1:" + m1.Name);
Person p1 = (Person)m1;
System.Console.WriteLine("2:" + p1.Name);
List<Manager> Managers = new List<Manager>();
List<Person> Persons = new List<Person>();
List<Pet> Pets = new List<Pet>();
Manager m2 = new Manager();
m2.Name = "Manager M2";
Managers.Add(m2);
Persons.Add(m2);
//Pets.Add(m2); // although Pet implements IMammal you can't
turn a manager into a pet - as much as we'd like to sometimes.
System.Threading.Thread.CurrentThread.Suspend();
}
}
interface IMammal
{
}
class Pet : IMammal
{
public string Name = String.Empty;
}
class Person : IMammal
{
public string Name = String.Empty;
}
class Manager : Person
{
public string Title = String.Empty;
}
}
------------------------ Yahoo! Groups Sponsor --------------------~--> You
can search right from your browser? It's easy and it's free. See how.
http://us.click.yahoo.com/_7bhrC/NGxNAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~->
Yahoo! Groups Links
Hey Dave thanks for your help and insight into casting to an Interface. I
understand what you mean, and I follow your example to the T. My only
problem is that I want Cast a list of one type to it's base which youdidn't
have an example of, something like this:
List<Person> Persons =Managers ;
DO I need to specifically cast it as follows?:
List<Person> Persons =(List<Person>)Managers ;
NO matter what I try I can't cast a list of a sublass to it's base. This
doesn't seem like something that MS wouldn't have thought about.
Thanks again.
Santiago Perez
Florida's Turnpike Enterprise
Programmer Analyst
Pompano Operations
Ph 954-975-4855 ex 1127
Cell 954-444-9429
"Dave Cline"
<davecline@gmail.
com> To
Sent by: StrongTypes@yahoogroups.com
StrongTypes@yahoo cc
groups.com
Subject
Re: [StrongTypes] Casting a
06/04/2006 06:08 SortedList Generic Class to a
PM generic Class of base type.
Please respond to
StrongTypes@yahoo
groups.com
I'm not expert, in anybody's book, but I believe you're trying to use an
interface like a base class. An interface is really just a signature, a
template if you will. It does not represent inheritance. Trying to cast an
object to it's interface well, that would be like trying to turn a person
into a painting. It can't be done without breaking a few laws of nature not
to mention Newtonian physics. But you can turn a person into a child, or
senior citizen or mammal or vertebrate. A picture of a person is really
just
a plan, a image of a three dimensional entity.
Try not using an interface as a generics type. Below was my testing rig.
But I maybe way off here.
DC
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfaceTesting
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Testing Inheritance");
Manager m1 = new Manager();
m1.Name = "Manager M1";
System.Console.WriteLine("1:" + m1.Name);
Person p1 = (Person)m1;
System.Console.WriteLine("2:" + p1.Name);
List<Manager> Managers = new List<Manager>();
List<Person> Persons = new List<Person>();
List<Pet> Pets = new List<Pet>();
Manager m2 = new Manager();
m2.Name = "Manager M2";
Managers.Add(m2);
Persons.Add(m2);
//Pets.Add(m2); // although Pet implements IMammal you can't
turn a manager into a pet - as much as we'd like to sometimes.
System.Threading.Thread.CurrentThread.Suspend();
}
}
interface IMammal
{
}
class Pet : IMammal
{
public string Name = String.Empty;
}
class Person : IMammal
{
public string Name = String.Empty;
}
class Manager : Person
{
public string Title = String.Empty;
}
}
[Non-text portions of this message have been removed]
SPONSORED LINKS
Object oriented Object oriented Object oriented
design language
Object oriented Object oriented Object oriented
training methodology tutorial
YAHOO! GROUPS LINKS
Visit your group "StrongTypes" on the web.
To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
I'm not expert, in anybody's book, but I believe you're trying to use an
interface like a base class. An interface is really just a signature, a
template if you will. It does not represent inheritance. Trying to cast an
object to it's interface well, that would be like trying to turn a person
into a painting. It can't be done without breaking a few laws of nature not
to mention Newtonian physics. But you can turn a person into a child, or
senior citizen or mammal or vertebrate. A picture of a person is really just
a plan, a image of a three dimensional entity.
Try not using an interface as a generics type. Below was my testing rig.
But I maybe way off here.
DC
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfaceTesting
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Testing Inheritance");
Manager m1 = new Manager();
m1.Name = "Manager M1";
System.Console.WriteLine("1:" + m1.Name);
Person p1 = (Person)m1;
System.Console.WriteLine("2:" + p1.Name);
List<Manager> Managers = new List<Manager>();
List<Person> Persons = new List<Person>();
List<Pet> Pets = new List<Pet>();
Manager m2 = new Manager();
m2.Name = "Manager M2";
Managers.Add(m2);
Persons.Add(m2);
//Pets.Add(m2); // although Pet implements IMammal you can't
turn a manager into a pet - as much as we'd like to sometimes.
System.Threading.Thread.CurrentThread.Suspend();
}
}
interface IMammal
{
}
class Pet : IMammal
{
public string Name = String.Empty;
}
class Person : IMammal
{
public string Name = String.Empty;
}
class Manager : Person
{
public string Title = String.Empty;
}
}
[Non-text portions of this message have been removed]
Funny thing is that I did exactly what you're talking about.
interface ILetter
{
}
class A : ILetter
{
private string _ID;
public string ID
{
get { return this._ID; }
set { this._ID = value; }
}
}
class B : A, ILetter
{
}
THen I have a button do the following:
private void button1_Click(object sender, EventArgs e)
{
Letters<B> L = new Letters<B>();
B oB = new B();
oB.ID = "1";
L.Add(oB.ID, oB);
Letters<ILetter> L2 = L;
}
I get : Error 1 Cannot implicitly convert type
'ProjectCentral_TESTAPP.Letters<ProjectCentral_TESTAPP.B>' to
'ProjectCentral_TESTAPP.Letters<ProjectCentral_TESTAPP.ILetter>'
C:\Projects\Vs2005\ProjectCentral\Libraries\ProjectCentral_TESTAPP\ProjectCentra\
l_TESTAPP\Form1.cs
40 35 ProjectCentral_TESTAPP
If try this I get the same thing:
Letters<A> L2 = L;
or
Letters<A> L2 = (Letters<A>)L;
I thought with Inheritance I could always cast a sublass to it's base.
What the heck???
FUnny thing is I can do this: A oA = oB;
but I can't do it with the generics
Santiago Perez
Florida's Turnpike Enterprise
Programmer Analyst
Pompano Operations
Ph 954-975-4855 ex 1127
Cell 954-444-9429
Error 2 Cannot implicitly convert type
'ProjectCentral.Contacts.Personnel_List<ProjectCentral.Contacts.Contract_Person>\
'
to
'ProjectCentral.Contacts.Personnel_List<ProjectCentral.Contacts.iPerson>'
C:\Inetpub\wwwroot\ProjectCentral\Contracts\ContractContacts.aspx.cs 43
40 http://localhost/ProjectCentral/
UcPersonnelList1.DataSource = ((Contract)this
.ContractDetail1.DataSource).Personnel_List;
UcPersonnelList1.DataSource is defined as
public Personnel_List<iPerson> DataSource { get; set; }
and Contract.Personnel_List is:
public ProjectCentral.Contacts.Personnel_List<Contract_Person>
Personnel_List
{
get
{ if (this._Personnel_List == null)
this._Personnel_List = new Personnel_List<
Contract_Person >();
return this._Personnel_List;
}
set
{
this.Personnel_List = value;
}
}
Santiago Perez
Florida's Turnpike Enterprise
Programmer Analyst
Pompano Operations
Ph 954-975-4855 ex 1127
Cell 954-444-9429
"Ryan Olshan"
<teranetlists@ter
anetsystems.com> To
Sent by: <StrongTypes@yahoogroups.com>
StrongTypes@yahoo cc
groups.com
Subject
RE: [StrongTypes] Casting a
06/02/2006 02:59 SortedList Generic Class to a
AM generic Class of base type.
Please respond to
StrongTypes@yahoo
groups.com
What is the exception or compiler error you are getting?
Thank you,
Ryan Olshan
Website - http://www.StrongTypes.com <http://www.strongtypes.com/>
Group - http://groups.yahoo.com/group/StrongTypes
Blog - http://blogs.strongcoders.com/blogs/ryan/
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of Santiago Perez
Sent: Thursday, June 01, 2006 11:10 AM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Casting a SortedList Generic Class to a generic
Class
of base type.
Hello everyone, this is my first post so please bare with me.
I am trying to understand why I can't cast generic class to a class
of a base type. I have the following setup:
///////////////////////////////////////////////////////////////////
public class Personnel_List<T> :
ProjectCentral.GlobalObjects.PersistentObject_List<Person_Abs> where
T : Person_Abs, iPerson
{
}
public abstract class Person_Abs :
ProjectCentral.GlobalObjects.PersistentObject, Contacts.iPerson
{
}
public class Vendor_Person : Person
{
}
public class Contract_Person : Vendor_Person
{
////////////////////////////////////////////////
Ok so now I have a contract class that has a property Personnel_List
which is
/////////////////////////////////////////////////////////////
public class Contract :
ProjectCentral.GlobalObjects.PersistentObject, iContract
{
public
ProjectCentral.Contacts.Personnel_List<Contacts.Contract_Person>
Personnel_List
{
get
{ if (this._Personnel_List == null)
this._Personnel_List = new
Personnel_List<Contract_Person>();
return this._Personnel_List;
}
set
{
this.Personnel_List = value;
}
}
}
//////////////////////////////////////////////////////////////////
THen I have a usercontrol that I want to use everywhere to list
Personnel so I set up a property as follows:
//////////////////////////////////////////////////////////
public Personnel_List<Person> DataSource
{
get { return (Personnel_List<Person>)
grdPersonnel.DataSource; }
set {grdPersonnel.DataSource = value;}
}
////////////////////////////////////////////////////////////
So when I try to do this it bombs on me:
///////////////////////////////////////////////////////////////
UcPersonnelList1.DataSource = ((Contract)
this.ContractDetail1.DataSource).Personnel_List;
////////////////////////////////////////////////////////////
Even if I try this:
///////////////////////////////////////////////////////////////
UcPersonnelList1.DataSource = (Personnel_List<Person>)((Contract)
this.ContractDetail1.DataSource).Personnel_List;
////////////////////////////////////////////////////////////
ANy help would be greatly appreciated. My boss is starting to look
at me like I don't know what I'm doing.
SPONSORED LINKS
Object
<
http://groups.yahoo.com/gads?t=ms&k=Object+oriented&w1=Object+oriented&w2=O
bject+oriented+design&w3=Object+oriented+language&w4=Object+oriented+trainin
g&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=172&.sig=
uLqg2pfGRplGmMsp6kJtVQ> oriented Object
<
http://groups.yahoo.com/gads?t=ms&k=Object+oriented+design&w1=Object+orient
ed&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriented+
training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=17
2&.sig=pGWYLp0sQpJs3JoBMlqbdA> oriented design Object
<
http://groups.yahoo.com/gads?t=ms&k=Object+oriented+language&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=oMxENFA3eiv-nKTwqk3z6Q> oriented language
Object
<
http://groups.yahoo.com/gads?t=ms&k=Object+oriented+training&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=WW87rn12Wb695fEwKFWRNg> oriented training Object
<
http://groups.yahoo.com/gads?t=ms&k=Object+oriented+methodology&w1=Object+o
riented&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+orie
nted+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6
&s=172&.sig=ZfydFONc8Llu8PBIVAyRuQ> oriented methodology Object
<
http://groups.yahoo.com/gads?t=ms&k=Object+oriented+tutorial&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=5RlQ7dXcE52DzP8Rq1Dbdg> oriented tutorial
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
SPONSORED LINKS
Object oriented Object oriented Object oriented
design language
Object oriented Object oriented Object oriented
training methodology tutorial
YAHOO! GROUPS LINKS
Visit your group "StrongTypes" on the web.
To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
What is the exception or compiler error you are getting?
Thank you,
Ryan Olshan
Website - http://www.StrongTypes.com <http://www.strongtypes.com/>
Group - http://groups.yahoo.com/group/StrongTypes
Blog - http://blogs.strongcoders.com/blogs/ryan/
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of Santiago Perez
Sent: Thursday, June 01, 2006 11:10 AM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Casting a SortedList Generic Class to a generic Class
of base type.
Hello everyone, this is my first post so please bare with me.
I am trying to understand why I can't cast generic class to a class
of a base type. I have the following setup:
///////////////////////////////////////////////////////////////////
public class Personnel_List<T> :
ProjectCentral.GlobalObjects.PersistentObject_List<Person_Abs> where
T : Person_Abs, iPerson
{
}
public abstract class Person_Abs :
ProjectCentral.GlobalObjects.PersistentObject, Contacts.iPerson
{
}
public class Vendor_Person : Person
{
}
public class Contract_Person : Vendor_Person
{
////////////////////////////////////////////////
Ok so now I have a contract class that has a property Personnel_List
which is
/////////////////////////////////////////////////////////////
public class Contract :
ProjectCentral.GlobalObjects.PersistentObject, iContract
{
public
ProjectCentral.Contacts.Personnel_List<Contacts.Contract_Person>
Personnel_List
{
get
{ if (this._Personnel_List == null)
this._Personnel_List = new
Personnel_List<Contract_Person>();
return this._Personnel_List;
}
set
{
this.Personnel_List = value;
}
}
}
//////////////////////////////////////////////////////////////////
THen I have a usercontrol that I want to use everywhere to list
Personnel so I set up a property as follows:
//////////////////////////////////////////////////////////
public Personnel_List<Person> DataSource
{
get { return (Personnel_List<Person>)
grdPersonnel.DataSource; }
set {grdPersonnel.DataSource = value;}
}
////////////////////////////////////////////////////////////
So when I try to do this it bombs on me:
///////////////////////////////////////////////////////////////
UcPersonnelList1.DataSource = ((Contract)
this.ContractDetail1.DataSource).Personnel_List;
////////////////////////////////////////////////////////////
Even if I try this:
///////////////////////////////////////////////////////////////
UcPersonnelList1.DataSource = (Personnel_List<Person>)((Contract)
this.ContractDetail1.DataSource).Personnel_List;
////////////////////////////////////////////////////////////
ANy help would be greatly appreciated. My boss is starting to look
at me like I don't know what I'm doing.
SPONSORED LINKS
Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented&w1=Object+oriented&w2=O
bject+oriented+design&w3=Object+oriented+language&w4=Object+oriented+trainin
g&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=172&.sig=
uLqg2pfGRplGmMsp6kJtVQ> oriented Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+design&w1=Object+orient
ed&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriented+
training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=17
2&.sig=pGWYLp0sQpJs3JoBMlqbdA> oriented design Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+language&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=oMxENFA3eiv-nKTwqk3z6Q> oriented language
Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+training&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=WW87rn12Wb695fEwKFWRNg> oriented training Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+methodology&w1=Object+o
riented&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+orie
nted+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6
&s=172&.sig=ZfydFONc8Llu8PBIVAyRuQ> oriented methodology Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+tutorial&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=5RlQ7dXcE52DzP8Rq1Dbdg> oriented tutorial
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
Hello everyone, this is my first post so please bare with me.
I am trying to understand why I can't cast generic class to a class
of a base type. I have the following setup:
///////////////////////////////////////////////////////////////////
public class Personnel_List<T> :
ProjectCentral.GlobalObjects.PersistentObject_List<Person_Abs> where
T : Person_Abs, iPerson
{
}
public abstract class Person_Abs :
ProjectCentral.GlobalObjects.PersistentObject, Contacts.iPerson
{
}
public class Vendor_Person : Person
{
}
public class Contract_Person : Vendor_Person
{
////////////////////////////////////////////////
Ok so now I have a contract class that has a property Personnel_List
which is
/////////////////////////////////////////////////////////////
public class Contract :
ProjectCentral.GlobalObjects.PersistentObject, iContract
{
public
ProjectCentral.Contacts.Personnel_List<Contacts.Contract_Person>
Personnel_List
{
get
{ if (this._Personnel_List == null)
this._Personnel_List = new
Personnel_List<Contract_Person>();
return this._Personnel_List;
}
set
{
this.Personnel_List = value;
}
}
}
//////////////////////////////////////////////////////////////////
THen I have a usercontrol that I want to use everywhere to list
Personnel so I set up a property as follows:
//////////////////////////////////////////////////////////
public Personnel_List<Person> DataSource
{
get { return (Personnel_List<Person>)
grdPersonnel.DataSource; }
set {grdPersonnel.DataSource = value;}
}
////////////////////////////////////////////////////////////
So when I try to do this it bombs on me:
///////////////////////////////////////////////////////////////
UcPersonnelList1.DataSource = ((Contract)
this.ContractDetail1.DataSource).Personnel_List;
////////////////////////////////////////////////////////////
Even if I try this:
///////////////////////////////////////////////////////////////
UcPersonnelList1.DataSource = (Personnel_List<Person>)((Contract)
this.ContractDetail1.DataSource).Personnel_List;
////////////////////////////////////////////////////////////
ANy help would be greatly appreciated. My boss is starting to look
at me like I don't know what I'm doing.
Since GetValue returns an object, you'd have to cast it to T.
public T RStoList<T>(SqlDataReader rdr, int index)
{
List<T> list = new List<T>();
while (rdr.Read())
{
list.Add((T)rdr.GetValue(index));
}
return list;
}
HTH,
Ryan
Thank you,
Ryan Olshan
Website - http://www.StrongTypes.com <http://www.strongtypes.com/>
Group - http://groups.yahoo.com/group/StrongTypes
Blog - http://blogs.strongcoders.com/blogs/ryan/
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of sureshotnj
Sent: Friday, May 12, 2006 1:02 PM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Generic SqlDataReader to List
I'm trying to loop through a reader and put all the values into a
generic list.
public T RStoList<T>(SqlDataReader rdr, int index)
{
List<T> list = new List<T>();
while (rdr.Read())
{
list.Add(rdr.GetValue(index));
}
return list;
}
It's not letting me add the object to the list though. I need to
somehow convert the value from the reader into the right type T.
Tried this without success:
list.Add(Convert.ChangeType(rdr.GetValue(index),typeof(T)));
Ideas?
SPONSORED LINKS
Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented&w1=Object+oriented&w2=O
bject+oriented+design&w3=Object+oriented+language&w4=Object+oriented+trainin
g&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=172&.sig=
uLqg2pfGRplGmMsp6kJtVQ> oriented Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+design&w1=Object+orient
ed&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriented+
training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=17
2&.sig=pGWYLp0sQpJs3JoBMlqbdA> oriented design Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+language&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=oMxENFA3eiv-nKTwqk3z6Q> oriented language
Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+training&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=WW87rn12Wb695fEwKFWRNg> oriented training Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+methodology&w1=Object+o
riented&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+orie
nted+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6
&s=172&.sig=ZfydFONc8Llu8PBIVAyRuQ> oriented methodology Object
<http://groups.yahoo.com/gads?t=ms&k=Object+oriented+tutorial&w1=Object+orie
nted&w2=Object+oriented+design&w3=Object+oriented+language&w4=Object+oriente
d+training&w5=Object+oriented+methodology&w6=Object+oriented+tutorial&c=6&s=
172&.sig=5RlQ7dXcE52DzP8Rq1Dbdg> oriented tutorial
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
I'm trying to loop through a reader and put all the values into a
generic list.
public T RStoList<T>(SqlDataReader rdr, int index)
{
List<T> list = new List<T>();
while (rdr.Read())
{
list.Add(rdr.GetValue(index));
}
return list;
}
It's not letting me add the object to the list though. I need to
somehow convert the value from the reader into the right type T.
Tried this without success:
list.Add(Convert.ChangeType(rdr.GetValue(index),typeof(T)));
Ideas?
I think Generics will solve my need for strong type casting with web
services but I am having a problem with the Web Service Code.
Any ideas on how to pass an Generic List(of T) as a Web Service.
<WebMethod()> _
Public Function List(ByVal RMARecId As Integer) As List(Of
TableDefs.RMA)
Dim obj As RMAs
obj = New RMAs
Return obj.List(RMARecId)
End Function
Public Function List(ByVal RMARecId As Integer) As
System.Collections.Generic.List(Of TableDefs.RMA) Implements
IRMAs.List
Dim dt As DataTable
dt = GetData(RMARecId)
Return CreateList(dt)
End Function
Thanks,
Mat
Thanks Ryan,
Ok, that wasn't the problem. I had that specified in the GridView
already. The problem was my function UpdateAllergy, this is what it
should be:
Public Function UpdateAllergy(ByVal a As Allergy) As Integer
Return AllergiesDB.UpdateAllergy(a.AllergyID, a.daycareCode,
a.AllergyEn, a.AllergyFr)
End Function
And what I had was "ByRef a As Allergy". Sheesh....for crying out
loud....I can't believe it. I didn't even notice that I changed it
for use in another area. I just wish it would have been easier to
trace the problem, like an error message that made a little more
sense.
--- In StrongTypes@yahoogroups.com, "Ryan Olshan" <teranetlists@...>
wrote:
>
> Hi Dave,
>
> This most likely has to do with the primary key. Make sure that
the primary
> key is included in the DataKeyNames property for the GridView.
>
> HTH
>
> Thank you,
> Ryan Olshan
> Website - http://www.StrongTypes.com
<http://www.strongtypes.com/>
> Group - http://groups.yahoo.com/group/StrongTypes
> Blog - http://blogs.dirteam.com/blogs/ryan/
>
>
> _____
>
> From: StrongTypes@yahoogroups.com
[mailto:StrongTypes@yahoogroups.com] On
> Behalf Of preludeandave
> Sent: Wednesday, February 15, 2006 10:18 PM
> To: StrongTypes@yahoogroups.com
> Subject: [StrongTypes] Generics: ObjectDataSource, GridView, and
BLL
>
>
> Hi everyone,
>
> I love the idea of generics and am trying to put it to use,
> following the samples given on www.asp.net tutorials,
specifically:
> http://www.asp.net/QuickStart/util/srcview.aspx?
>
path=~/aspnet/samples/data/GridViewObject.src&file=GridViewObject_vb\
> GridViewObject_vb.aspx&lang=VB+Source
>
> I've set up my GridView to access the ObjectDataSource, and my ODS
> is set up as:
> <asp:ObjectDataSource ID="AllergyODS" Runat="server"
> TypeName="AllergiesComponent"
>
> SelectMethod="GetAllergies" UpdateMethod="UpdateAllergy"
> DataObjectTypeName="Allergy" SortParameterName="SortExpression">
>
> </asp:ObjectDataSource>
>
> However, whenever I hit Update, I get the dreaded:
> ObjectDataSource 'AllergyODS' could not find a non-generic
> method 'UpdateAllergy' that takes parameters of type 'Allergy'.
>
> Does anybody have a clue:
> a) why this doesn't work as per the examples supplied on asp.net?
> b) how I can find the signature of the function that it is trying
to
> call?
>
> Thanks,
> Dave
>
>
>
>
>
>
>
>
> _____
>
> YAHOO! GROUPS LINKS
>
>
>
> * Visit your group "StrongTypes
> <http://groups.yahoo.com/group/StrongTypes> " on the web.
>
>
> * To unsubscribe from this group, send an email to:
> StrongTypes-unsubscribe@yahoogroups.com
> <mailto:StrongTypes-unsubscribe@yahoogroups.com?
subject=Unsubscribe>
>
>
> * Your use of Yahoo! Groups is subject to the Yahoo! Terms of
Service
> <http://docs.yahoo.com/info/terms/> .
>
>
> _____
>
>
>
>
> [Non-text portions of this message have been removed]
>
Hi Dave,
This most likely has to do with the primary key. Make sure that the primary
key is included in the DataKeyNames property for the GridView.
HTH
Thank you,
Ryan Olshan
Website - http://www.StrongTypes.com <http://www.strongtypes.com/>
Group - http://groups.yahoo.com/group/StrongTypes
Blog - http://blogs.dirteam.com/blogs/ryan/
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of preludeandave
Sent: Wednesday, February 15, 2006 10:18 PM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Generics: ObjectDataSource, GridView, and BLL
Hi everyone,
I love the idea of generics and am trying to put it to use,
following the samples given on www.asp.net tutorials, specifically:
http://www.asp.net/QuickStart/util/srcview.aspx?
path=~/aspnet/samples/data/GridViewObject.src&file=GridViewObject_vb\
GridViewObject_vb.aspx&lang=VB+Source
I've set up my GridView to access the ObjectDataSource, and my ODS
is set up as:
<asp:ObjectDataSource ID="AllergyODS" Runat="server"
TypeName="AllergiesComponent"
SelectMethod="GetAllergies" UpdateMethod="UpdateAllergy"
DataObjectTypeName="Allergy" SortParameterName="SortExpression">
</asp:ObjectDataSource>
However, whenever I hit Update, I get the dreaded:
ObjectDataSource 'AllergyODS' could not find a non-generic
method 'UpdateAllergy' that takes parameters of type 'Allergy'.
Does anybody have a clue:
a) why this doesn't work as per the examples supplied on asp.net?
b) how I can find the signature of the function that it is trying to
call?
Thanks,
Dave
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
Hi everyone,
I love the idea of generics and am trying to put it to use,
following the samples given on www.asp.net tutorials, specifically:
http://www.asp.net/QuickStart/util/srcview.aspx?
path=~/aspnet/samples/data/GridViewObject.src&file=GridViewObject_vb\
GridViewObject_vb.aspx&lang=VB+Source
I've set up my GridView to access the ObjectDataSource, and my ODS
is set up as:
<asp:ObjectDataSource ID="AllergyODS" Runat="server"
TypeName="AllergiesComponent"
SelectMethod="GetAllergies" UpdateMethod="UpdateAllergy"
DataObjectTypeName="Allergy" SortParameterName="SortExpression">
</asp:ObjectDataSource>
However, whenever I hit Update, I get the dreaded:
ObjectDataSource 'AllergyODS' could not find a non-generic
method 'UpdateAllergy' that takes parameters of type 'Allergy'.
Does anybody have a clue:
a) why this doesn't work as per the examples supplied on asp.net?
b) how I can find the signature of the function that it is trying to
call?
Thanks,
Dave
Thank you Chris for your help. I really appreciate it....................
Chris Mohan <chrismohan@...> wrote: Oh, man--i got all caught up in
my answer and lost sight of the original
question, sorry 'bout that.
The design guidelines touch on the answer. From here:
http://blogs.msdn.com/kcwalina/archive/2004/03/15/89860.aspx
Do return Collection<T> from object models to provide standard plain vanilla
collection API.
public Collection<Session> Sessions { get; }
Do return a subclass of Collection<T> from object models to provide
high-level collection API.
public class ListItemCollection : Collection<ListItem> {}
public class ListBox {
public ListItemCollection Items { get; }
}
"Do not return List<T> from object models. Use Collection<T> instead.
List<T> is meant to be used for implementation, not in object model APIs.
List<T> is optimized for performance at the cost of long term versioning.
For example, if you return List<T> to the client code, you will not ever be
able to receive notifications when client code modifies the collection."
Personally-- the last point makes me want to prefer the use of List<T>
unless the context of use actually has a need to "receive notifications"
_____
From: Chris Mohan [mailto:chrismohan@...]
Sent: Saturday, February 04, 2006 12:13 AM
To: 'StrongTypes@yahoogroups.com'
Subject: RE: [StrongTypes] Why use Generics Collection<> rather than List<>
I don't see an advantage to using generics in this scenario; (whether its
Collection<T> or List<T>). I see a disadvantage since a generic object is
used in conjunction with a dataset and the implementation of the method is
tightly coupled to a specific type (product) instead of being loosely
coupled to a parameterized type of T.
The key part of the code (as it appears to me) is:
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
If you have a reason for, or don't mind, the tight coupling to type Product
consider foregoing the use of a dataset in favor of a dataReader. W/ a
dataReader, create instances of product objects while adding them
Collection<Product> as you read from the datareader (in 1.1 you'd have had
to create your own strongly typed collection object of product that
inherited from Collection base. Using Collection<Product> frees you from
having to write strongly typed collection classes like that.
ie:
SqlDataReader dr = dbCommand.ExecuteReader();
Collection<Product> products = new Collection<product>();
While dr.Read {
products.Add(new product(dr.Getint32(0), dr.GetString(1), etc, etc))
}
Return products
Reasoning as to why the above is preferable to the original sample:
When you call ExecuteDataSet you're already getting all the product data in
a strongly typed collection object (products.Tables[0].Rows, an instance of
a DataRowCollection object). Datasets have more overhead than most other
collection objects. An instance of a dataset is an in memory representation
of a database; it's a complex type composed of other complex objects as its
properties. DataSet.Tables is an instance of a DataTableCollection whose
Rows property is an instance of a DataRowCollection object in which each
item is a dataRow that has a Column property of type dataColumn, etc, etc).
The example you sent appears to only use 1 table from the dataset's
collection of tables (productDataSet.Tables[0]). In these cases you can get
the same effect by using 1 datatable instead of a dataset and avoid the
overhead created by the extra parts of the dataset that the code does not
use (objects that represent constraints and relations between the tables in
the collection of tables and possibly others.)
From what I've read, generics can improve performance, but they do so
disproportionably for value types. For reference types, i've read estimates
that claim they boost performance anywhere from 20% (
<http://msdn.microsoft.com/msdnmag/issues/06/00/NET/default.aspx>
http://msdn.microsoft.com/msdnmag/issues/06/00/NET/default.aspx) to 100% (
<http://www.amazon.com/gp/product/0764559885>
http://www.amazon.com/gp/product/0764559885 ). It depends on how they're
used: storing say 2 instances of T in Collection<T> might get less
performance than if you just used an array with two elements of type T. The
second link referenced above claims that when T in Collection<T> is a Value
type- you can experience an increase in performance by as much as 200% --
b/c generics are strongly typed, when T is a value type you to avoid boxing
and unboxing each item in the collection.
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of successin06x
Sent: Friday, February 03, 2006 1:06 PM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Why use Generics Collection<> rather than List<>
Refering to this which I found on Microsoft's site: List<T> is
basically a better ArrayList. It is optimized for speed, size, and
power. Use it for majority of internal implementations whenever you
need to store items in a container. "Do not use it in public APIs."
Does it matter in this case:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.EnterpriseLibrary.Data;
/// <summary>
/// Summary description for Product
/// </summary>
public class Product
{
#region Fields and Properties
private string _productName;
public string ProductName
{
get { return _productName; }
protected set { _productName = value; }
}
private int _unitPrice;
public int UnitPrice
{
get { return _unitPrice; }
protected set { _unitPrice = value; }
}
#endregion
public Product()
{
//
// TODO: Add constructor logic here
//
}
public static Collection<Product> GetSalesByCategory()
{
Database myDB = DatabaseFactory.CreateDatabase();
string sqlCommand = "Ten Most Expensive Products";
DbCommand dbCommand = myDB.GetStoredProcCommand(sqlCommand);
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
}
}
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
SPONSORED LINKS
Object oriented programming language Object oriented Programming
languages
---------------------------------
YAHOO! GROUPS LINKS
Visit your group "StrongTypes" on the web.
To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
---------------------------------
---------------------------------
Yahoo! Mail
Use Photomail to share photos without annoying attachments.
[Non-text portions of this message have been removed]
I don't see an advantage to using generics in this scenario; (whether its
Collection<T> or List<T>). I see a disadvantage since a generic object is
used in conjunction with a dataset and the implementation of the method is
tightly coupled to a specific type (product) instead of being loosely
coupled to a parameterized type of T.
The key part of the code (as it appears to me) is:
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
If you have a reason for, or don't mind, the tight coupling to type Product
consider foregoing the use of a dataset in favor of a dataReader. W/ a
dataReader, create instances of product objects while adding them
Collection<Product> as you read from the datareader (in 1.1 you'd have had
to create your own strongly typed collection object of product that
inherited from Collection base. Using Collection<Product> frees you from
having to write strongly typed collection classes like that.
ie:
SqlDataReader dr = dbCommand.ExecuteReader();
Collection<Product> products = new Collection<product>();
While dr.Read {
products.Add(new product(dr.Getint32(0), dr.GetString(1), etc, etc))
}
Return products
Reasoning as to why the above is preferable to the original sample:
When you call ExecuteDataSet you're already getting all the product data in
a strongly typed collection object (products.Tables[0].Rows, an instance of
a DataRowCollection object). Datasets have more overhead than most other
collection objects. An instance of a dataset is an in memory representation
of a database; it's a complex type composed of other complex objects as its
properties. DataSet.Tables is an instance of a DataTableCollection whose
Rows property is an instance of a DataRowCollection object in which each
item is a dataRow that has a Column property of type dataColumn, etc, etc).
The example you sent appears to only use 1 table from the dataset's
collection of tables (productDataSet.Tables[0]). In these cases you can get
the same effect by using 1 datatable instead of a dataset and avoid the
overhead created by the extra parts of the dataset that the code does not
use (objects that represent constraints and relations between the tables in
the collection of tables and possibly others.)
From what I've read, generics can improve performance, but they do so
disproportionably for value types. For reference types, i've read estimates
that claim they boost performance anywhere from 20% (
<http://msdn.microsoft.com/msdnmag/issues/06/00/NET/default.aspx>
http://msdn.microsoft.com/msdnmag/issues/06/00/NET/default.aspx) to 100% (
<http://www.amazon.com/gp/product/0764559885>
http://www.amazon.com/gp/product/0764559885 ). It depends on how they're
used: storing say 2 instances of T in Collection<T> might get less
performance than if you just used an array with two elements of type T. The
second link referenced above claims that when T in Collection<T> is a Value
type- you can experience an increase in performance by as much as 200% --
b/c generics are strongly typed, when T is a value type you to avoid boxing
and unboxing each item in the collection.
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of successin06x
Sent: Friday, February 03, 2006 1:06 PM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Why use Generics Collection<> rather than List<>
Refering to this which I found on Microsoft's site: List<T> is
basically a better ArrayList. It is optimized for speed, size, and
power. Use it for majority of internal implementations whenever you
need to store items in a container. "Do not use it in public APIs."
Does it matter in this case:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.EnterpriseLibrary.Data;
/// <summary>
/// Summary description for Product
/// </summary>
public class Product
{
#region Fields and Properties
private string _productName;
public string ProductName
{
get { return _productName; }
protected set { _productName = value; }
}
private int _unitPrice;
public int UnitPrice
{
get { return _unitPrice; }
protected set { _unitPrice = value; }
}
#endregion
public Product()
{
//
// TODO: Add constructor logic here
//
}
public static Collection<Product> GetSalesByCategory()
{
Database myDB = DatabaseFactory.CreateDatabase();
string sqlCommand = "Ten Most Expensive Products";
DbCommand dbCommand = myDB.GetStoredProcCommand(sqlCommand);
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
}
}
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
Oh, man--i got all caught up in my answer and lost sight of the original
question, sorry 'bout that.
The design guidelines touch on the answer. From here:
http://blogs.msdn.com/kcwalina/archive/2004/03/15/89860.aspx
Do return Collection<T> from object models to provide standard plain vanilla
collection API.
public Collection<Session> Sessions { get; }
Do return a subclass of Collection<T> from object models to provide
high-level collection API.
public class ListItemCollection : Collection<ListItem> {}
public class ListBox {
public ListItemCollection Items { get; }
}
"Do not return List<T> from object models. Use Collection<T> instead.
List<T> is meant to be used for implementation, not in object model APIs.
List<T> is optimized for performance at the cost of long term versioning.
For example, if you return List<T> to the client code, you will not ever be
able to receive notifications when client code modifies the collection."
Personally-- the last point makes me want to prefer the use of List<T>
unless the context of use actually has a need to "receive notifications"
_____
From: Chris Mohan [mailto:chrismohan@...]
Sent: Saturday, February 04, 2006 12:13 AM
To: 'StrongTypes@yahoogroups.com'
Subject: RE: [StrongTypes] Why use Generics Collection<> rather than List<>
I don't see an advantage to using generics in this scenario; (whether its
Collection<T> or List<T>). I see a disadvantage since a generic object is
used in conjunction with a dataset and the implementation of the method is
tightly coupled to a specific type (product) instead of being loosely
coupled to a parameterized type of T.
The key part of the code (as it appears to me) is:
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
If you have a reason for, or don't mind, the tight coupling to type Product
consider foregoing the use of a dataset in favor of a dataReader. W/ a
dataReader, create instances of product objects while adding them
Collection<Product> as you read from the datareader (in 1.1 you'd have had
to create your own strongly typed collection object of product that
inherited from Collection base. Using Collection<Product> frees you from
having to write strongly typed collection classes like that.
ie:
SqlDataReader dr = dbCommand.ExecuteReader();
Collection<Product> products = new Collection<product>();
While dr.Read {
products.Add(new product(dr.Getint32(0), dr.GetString(1), etc, etc))
}
Return products
Reasoning as to why the above is preferable to the original sample:
When you call ExecuteDataSet you're already getting all the product data in
a strongly typed collection object (products.Tables[0].Rows, an instance of
a DataRowCollection object). Datasets have more overhead than most other
collection objects. An instance of a dataset is an in memory representation
of a database; it's a complex type composed of other complex objects as its
properties. DataSet.Tables is an instance of a DataTableCollection whose
Rows property is an instance of a DataRowCollection object in which each
item is a dataRow that has a Column property of type dataColumn, etc, etc).
The example you sent appears to only use 1 table from the dataset's
collection of tables (productDataSet.Tables[0]). In these cases you can get
the same effect by using 1 datatable instead of a dataset and avoid the
overhead created by the extra parts of the dataset that the code does not
use (objects that represent constraints and relations between the tables in
the collection of tables and possibly others.)
From what I've read, generics can improve performance, but they do so
disproportionably for value types. For reference types, i've read estimates
that claim they boost performance anywhere from 20% (
<http://msdn.microsoft.com/msdnmag/issues/06/00/NET/default.aspx>
http://msdn.microsoft.com/msdnmag/issues/06/00/NET/default.aspx) to 100% (
<http://www.amazon.com/gp/product/0764559885>
http://www.amazon.com/gp/product/0764559885 ). It depends on how they're
used: storing say 2 instances of T in Collection<T> might get less
performance than if you just used an array with two elements of type T. The
second link referenced above claims that when T in Collection<T> is a Value
type- you can experience an increase in performance by as much as 200% --
b/c generics are strongly typed, when T is a value type you to avoid boxing
and unboxing each item in the collection.
_____
From: StrongTypes@yahoogroups.com [mailto:StrongTypes@yahoogroups.com] On
Behalf Of successin06x
Sent: Friday, February 03, 2006 1:06 PM
To: StrongTypes@yahoogroups.com
Subject: [StrongTypes] Why use Generics Collection<> rather than List<>
Refering to this which I found on Microsoft's site: List<T> is
basically a better ArrayList. It is optimized for speed, size, and
power. Use it for majority of internal implementations whenever you
need to store items in a container. "Do not use it in public APIs."
Does it matter in this case:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.EnterpriseLibrary.Data;
/// <summary>
/// Summary description for Product
/// </summary>
public class Product
{
#region Fields and Properties
private string _productName;
public string ProductName
{
get { return _productName; }
protected set { _productName = value; }
}
private int _unitPrice;
public int UnitPrice
{
get { return _unitPrice; }
protected set { _unitPrice = value; }
}
#endregion
public Product()
{
//
// TODO: Add constructor logic here
//
}
public static Collection<Product> GetSalesByCategory()
{
Database myDB = DatabaseFactory.CreateDatabase();
string sqlCommand = "Ten Most Expensive Products";
DbCommand dbCommand = myDB.GetStoredProcCommand(sqlCommand);
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
}
}
_____
YAHOO! GROUPS LINKS
* Visit your group "StrongTypes
<http://groups.yahoo.com/group/StrongTypes> " on the web.
* To unsubscribe from this group, send an email to:
StrongTypes-unsubscribe@yahoogroups.com
<mailto:StrongTypes-unsubscribe@yahoogroups.com?subject=Unsubscribe>
* Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service
<http://docs.yahoo.com/info/terms/> .
_____
[Non-text portions of this message have been removed]
Looks like you are using a collection and not an API. I think its fine.
On 2/3/06, successin06x <successin06x@...> wrote:
>
> Refering to this which I found on Microsoft's site: List<T> is
> basically a better ArrayList. It is optimized for speed, size, and
> power. Use it for majority of internal implementations whenever you
> need to store items in a container. "Do not use it in public APIs."
>
> Does it matter in this case:
>
> using System;
>
> using System.Data;
>
> using System.Configuration;
>
> using System.Web;
>
> using System.Web.Security;
>
> using System.Web.UI;
>
> using System.Web.UI.WebControls;
>
> using System.Web.UI.WebControls.WebParts;
>
> using System.Data.Common;
>
> using System.Web.UI.HtmlControls;
>
> using System.Collections.Generic;
>
> using System.Collections.ObjectModel;
>
> using Microsoft.Practices.EnterpriseLibrary.Data;
>
> /// <summary>
>
> /// Summary description for Product
>
> /// </summary>
>
> public class Product
>
> {
>
> #region Fields and Properties
>
> private string _productName;
>
> public string ProductName
>
> {
>
> get { return _productName; }
>
> protected set { _productName = value; }
>
> }
>
> private int _unitPrice;
>
> public int UnitPrice
>
> {
>
> get { return _unitPrice; }
>
> protected set { _unitPrice = value; }
>
> }
>
> #endregion
>
>
> public Product()
>
> {
>
> //
>
> // TODO: Add constructor logic here
>
> //
>
> }
>
> public static Collection<Product> GetSalesByCategory()
>
> {
>
> Database myDB = DatabaseFactory.CreateDatabase();
>
> string sqlCommand = "Ten Most Expensive Products";
>
> DbCommand dbCommand = myDB.GetStoredProcCommand(sqlCommand);
>
> DataSet productDataSet = null;
>
> productDataSet = myDB.ExecuteDataSet(dbCommand);
>
> Collection<Product> products = new Collection<Product>();
>
> foreach(DataRow row in productDataSet.Tables[0].Rows)
>
> {
>
> Product p = new Product();
>
> p.ProductName = row["TenMostExpensiveProducts"].ToString();
>
> p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
>
> products.Add(p);
>
> }
>
> return products;
>
> }
>
> }
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> ------------------------------
> YAHOO! GROUPS LINKS
>
>
> - Visit your group
"StrongTypes<http://groups.yahoo.com/group/StrongTypes>"
> on the web.
>
> - To unsubscribe from this group, send an email to:
>
StrongTypes-unsubscribe@yahoogroups.com<StrongTypes-unsubscribe@yahoogroups.com?\
subject=Unsubscribe>
>
> - Your use of Yahoo! Groups is subject to the Yahoo! Terms of
> Service <http://docs.yahoo.com/info/terms/>.
>
>
> ------------------------------
>
--
Eric Ramseur
Microsoft.NET Consultant
------------------------
http://eramseur.blogspot.com | ASP.NET 2.0 Questions
http://anant.us/blog | Anant ASP.NET 2.0 CMS | Portal Blogs [ free blogs]
http://url123.com/xe7pd | C# 2.0 Group on Yahoo!
"Chance favors the prepared Mind"
[Non-text portions of this message have been removed]
Refering to this which I found on Microsoft's site: List<T> is
basically a better ArrayList. It is optimized for speed, size, and
power. Use it for majority of internal implementations whenever you
need to store items in a container. "Do not use it in public APIs."
Does it matter in this case:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.EnterpriseLibrary.Data;
/// <summary>
/// Summary description for Product
/// </summary>
public class Product
{
#region Fields and Properties
private string _productName;
public string ProductName
{
get { return _productName; }
protected set { _productName = value; }
}
private int _unitPrice;
public int UnitPrice
{
get { return _unitPrice; }
protected set { _unitPrice = value; }
}
#endregion
public Product()
{
//
// TODO: Add constructor logic here
//
}
public static Collection<Product> GetSalesByCategory()
{
Database myDB = DatabaseFactory.CreateDatabase();
string sqlCommand = "Ten Most Expensive Products";
DbCommand dbCommand = myDB.GetStoredProcCommand(sqlCommand);
DataSet productDataSet = null;
productDataSet = myDB.ExecuteDataSet(dbCommand);
Collection<Product> products = new Collection<Product>();
foreach(DataRow row in productDataSet.Tables[0].Rows)
{
Product p = new Product();
p.ProductName = row["TenMostExpensiveProducts"].ToString();
p.UnitPrice = Convert.ToInt32(row["UnitPrice"]);
products.Add(p);
}
return products;
}
}
I recommend Ryan's site.
On 12/14/05, teranetlists <Ryan.Olshan@...> wrote:
> StrongTypes.com is an excellent resource for learning about Generics.
> Learnasp.com some ASP.NET 2.0 examples and http://www.asp.net is the
> offical site for ASP.NET.
>
> /Ryan
>
> --- In StrongTypes@yahoogroups.com, "byj_joseph" <byj_joseph@y...>
>
> wrote:
> >
> > Please tell me some good sites for learning about Generics and other
> > new features of .net
> >
>
>
>
>
>
>
>
>
> ________________________________
> YAHOO! GROUPS LINKS
>
>
> Visit your group "StrongTypes" on the web.
>
> To unsubscribe from this group, send an email to:
> StrongTypes-unsubscribe@yahoogroups.com
>
> Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
>
> ________________________________
>
--
Eric Ramseur
.NET Consultant | ASP.NET Questions
http://eramseur.blogspot.com
"Chance favors the prepared Mind"
StrongTypes.com is an excellent resource for learning about Generics.
Learnasp.com some ASP.NET 2.0 examples and http://www.asp.net is the
offical site for ASP.NET.
/Ryan
--- In StrongTypes@yahoogroups.com, "byj_joseph" <byj_joseph@y...>
wrote:
>
> Please tell me some good sites for learning about Generics and other
> new features of .net
>
Welcome to the group rob. Its good to have a season veteran.
On 12/13/05, teranetlists <Ryan.Olshan@...> wrote:
> Welcome to the group. We look forward to providing expert .NET
> Generics help.
>
> --
> Thank you,
> Ryan Olshan
> Website - http://www.StrongTypes.com
> <Rolog> - http://blogs.dirteam.com/blogs/ryan/
>
>
> --- In StrongTypes@yahoogroups.com, "nboboloo" <tutor@e...> wrote:
> >
> > :)
> >
> > just thought I'd have to say that since this is the first time in 30
> > years of doing this I've been the first to post on a list.
> >
> > rob
> >
>
>
>
>
>
>
>
> ________________________________
> YAHOO! GROUPS LINKS
>
>
> Visit your group "StrongTypes" on the web.
>
> To unsubscribe from this group, send an email to:
> StrongTypes-unsubscribe@yahoogroups.com
>
> Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.
>
> ________________________________
>
--
Eric Ramseur
.NET Consultant
cell: 540-207-6403
"Chance favors the prepared Mind"
http://ramseur.net
The first time I heard about generics I didn't understand what they
were until I read the c# 2.0 spec. It's awesome how far templates
from C++ have come.
I think we have yet to discover how to use them in the web arena.
--- In StrongTypes@yahoogroups.com, "nboboloo" <tutor@e...> wrote:
>
> :)
>
> just thought I'd have to say that since this is the first time in 30
> years of doing this I've been the first to post on a list.
>
> rob
>
Welcome to the group. We look forward to providing expert .NET
Generics help.
--
Thank you,
Ryan Olshan
Website - http://www.StrongTypes.com
<Rolog> - http://blogs.dirteam.com/blogs/ryan/
--- In StrongTypes@yahoogroups.com, "nboboloo" <tutor@e...> wrote:
>
> :)
>
> just thought I'd have to say that since this is the first time in 30
> years of doing this I've been the first to post on a list.
>
> rob
>