Click to See Complete Forum and Search --> : Newbie generics question


LoneRanger
October 20th, 2008, 04:55 AM
Hi all,

I'm using C# in .NET 3.5 to load xml files, defined by xsd schemas. I'm using LinQ to xsd which generates objects for me, using the xsd schemas. All my schemas have a root node which is a complex type containing a sequence of objects. e.g.


<xs:element name="ObjectList">
<xs:complexType>
<xs:sequence>
<xs:element ref="MyObject" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:element>

<xs:element name="MyObject">
<xs:complexType>
<xs:all>
<xs:element name="ID" type="xs:string" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>


On compliation, the compiler generates an "ObjectList" class, which derives from XTypedElement. This contains a member, IList<MyObject> where MyObject also derives from XTypedElement. I can load the objects into memory easily using


var rootlist = ObjectList.Load(filepath);
IList<MyObject> = rootlist.MyObject;


Now what I want to do is to write a generic load function for all my objects (I have lots and lots of xsd schemas). I'm a bit stuck on how to do this. In C++ it's easy because you can create a list of XTypedElement pointers and initialise the list contents depending on what object type you are considering. However it's not good practice to use pointers in C# is it. I've had a look at generics but have come a bit unstuck. Does anyone have any tips on what sort of method I should be using?

Thanks in advance for your help.

JonnyPoet
October 20th, 2008, 05:05 AM
var rootlist = ObjectList.Load(filepath);
IList<MyObject> = rootlist.MyObject;

You are obviously talking about

var rootlist = ObjectList.Load(filepath);
IList<MyObject> myElements = rootlist.MyObject;
The myElements List will contain all your MyObject objects so whats the problem ? IList is already generic as you see so whats the problem ? If you have for example objects of customers and objects of products and other very different objects you cannot do other then building different lists for each of them like

IList<Customer> customers= rootlist.Customers;
IList<Product> product = rootlist.products;
This cannot be simplified any more IMHO

LoneRanger
October 20th, 2008, 05:08 AM
Yeah, sorry, typo there. The problem is that I don't want to write a separate load function for each of my 40+ xsd files (and hence object types). I want to write one generic load function that returns a list of the relevant object types.