new operator with deep class structure

Hi,

I generated C# classes from some complex XMLSchemas usind xsd.exe. The
result is that I get a class hierarchy that is quite deep (well for me
8 levels are deep). What I'm curiuos about is, that if I create an
instance of my top level element I still need to create instances of
all sub-elements. What would be the best way to do some sort of "deep
new" operator, that recursively creates instances for all sub-classes
(the complete structure consists of 89 different classes).

Lets say my class structure is like
Top
+-->Sub1
      +-->Sub1_1
      +-->Sub1_2
+-->Sub2
      +-->Sub2_1
      +-->Sub2_2

and instead of:
Top top = new Top();
top.sub1 = new Sub1();
top.sub1.sub1_1 = new Sub1_1();
top.sub1.sub1_2 = new Sub1_2();
....

just do:
Top top = new Top(true);

which will create instances for all sub-elements.

Of couse I could code a creator method that just does this. But maybe
this is not the best approach. So what would a experienced C#-guy do?
Any idea?

Thanks,
Stefan

P.S.: You probably noticed that I must be new to C#/FW2.0...

0
7/28/2007 1:39:11 PM
dotnet.xml 7266 articles. 0 followers. Follow

8 Replies
829 Views

Similar Articles

[PageSpeed] 57

<olympus_mons@gmx.de> wrote in message 
news:1185629951.084096.12290@l70g2000hse.googlegroups.com...
> Hi,
>
> I generated C# classes from some complex XMLSchemas usind xsd.exe. The
> result is that I get a class hierarchy that is quite deep (well for me
> 8 levels are deep). What I'm curiuos about is, that if I create an
> instance of my top level element I still need to create instances of
> all sub-elements. What would be the best way to do some sort of "deep
> new" operator, that recursively creates instances for all sub-classes
> (the complete structure consists of 89 different classes).
>
> Lets say my class structure is like
> Top
> +-->Sub1
>      +-->Sub1_1
>      +-->Sub1_2
> +-->Sub2
>      +-->Sub2_1
>      +-->Sub2_2
>
> and instead of:
> Top top = new Top();
> top.sub1 = new Sub1();
> top.sub1.sub1_1 = new Sub1_1();
> top.sub1.sub1_2 = new Sub1_2();
> ...
>
> just do:
> Top top = new Top(true);
>
> which will create instances for all sub-elements.
>
> Of couse I could code a creator method that just does this. But maybe
> this is not the best approach. So what would a experienced C#-guy do?
> Any idea?
>
> Thanks,
> Stefan
>
> P.S.: You probably noticed that I must be new to C#/FW2.0...
>

Are your classes related via inheritance? I.e. is Sub1 a subclass of Top and 
are Sub1_1 and Sub1_2 subclasses of Sub1?
Are you actually trying to instantiate all the classes (Top, Sub1, Sub1_1 
and Sub1_2), or are you just trying to instantiate the subclasses (Sub1_1 
and Sub1_2)?
I'm asking because your example:
<quote>
just do:
Top top = new Top(true);

which will create instances for all sub-elements.
</quote>
seems to indicate that you don't understand how inheritance works.
In the example above, instantiating Sub1_1 calls constructors for Top, Sub1 
and Sub1_1 in that order, creating a "complete" instance of  Sub1_1.
Unless you have a specific need for the superclass instances as well as 
Sub1_1 and Sub1_2 instances, there's no point in creating them.
If you implement your Top top = new Top(true), do you plan to add parameters 
to indicate how many instances of each subclass to create?

If I've misunderstood your post, please excuse these ramblings.


0
pvdg (5)
7/28/2007 2:07:41 PM
Yes - you are right, I did not make this point very clear. The top
level class contains members which are of the sub class types. And the
sub-level members in turn contain members which are of typ sub-sub-
level class and so on. Sorry about the confusion.

Stefan

0
7/28/2007 4:41:55 PM
olympus_mons@gmx.de wrote:
> I generated C# classes from some complex XMLSchemas usind xsd.exe. The
> result is that I get a class hierarchy that is quite deep (well for me
> 8 levels are deep). What I'm curiuos about is, that if I create an
> instance of my top level element I still need to create instances of
> all sub-elements. What would be the best way to do some sort of "deep
> new" operator, that recursively creates instances for all sub-classes
> (the complete structure consists of 89 different classes).


I agree with the person posting as "PvdG42" that your question is confusing.

Terms like "class hierarchy" and "sub-class" do imply that you're using 
inheritance.  On the other hand, inheritance relates to the classes 
themselves, not the instances of the classes.  As "PvdG42" says, you 
don't need to instantiate any of the base classes in order to 
instantiate the most-derived class in that hierarchy chain.

Your example seems to reinforce that this is in fact what you're talking 
about.

However, it seems that there may be a possibility that you aren't 
actually dealing with a class hierarchy, but instead a data hierarchy. 
In which case, instantiating multiple instances based on your data may 
actually make sense.

This is also consistent with your claim that you are new to C#. 
Creating new classes programmatically is not the sort of thing someone 
new to C# would be likely to be doing, but creating a hierarchical data 
tree is.

Perhaps you can clarify what the actual scenario is.  In particular, are 
you actually creating classes dynamically, in which you have something 
that would look something like this:

     class Top {}
     class Sub1 : Top {}
     class Sub1_1 : Sub1 {}

etc.

If not, then you aren't actually creating a class hierarchy, nor are you 
creating sub-classes, in spite of what you wrote.

Pete
0
7/28/2007 4:59:49 PM
Pete and "PvdG42",

just to make it clear I provide a sample of what XSD.EXE created from
the XMLSchemas:

My top class is "Balance":

public partial class Balance
{
   private BalanceGeneral generalField;
   private BalanceAssets assetsField;
   private BalanceLiabilities liabilitiesField;

   // followed by correspondig get/set property methods
   public BalanceGeneral general
   {
      get
      {
         return this.generalField;
      }
      set
      {
         this.generalField = value;
      }
   }
   public BalanceAssets assets
   {
      // get/set for assetsField
   }
}

public partial class BalanceGeneral
{
   private System.DatTime effectiveDateField;
   private int numberOfEmployeesField;
   ...
   // followed by correspondig get/set property methods
   public DateTime effectiveDate
   {
      // get/set for effectiveDateField
   }
   ...
}

public partial class BalanceAssets
{
   ...
   private BalanceAssetsStocks stocksField;
   ...
}

Again: there is no inheritance involved. Each class consist of member
fields that are either simple types (as DateTime, int or decimal) or
class types like BalanceGeneral or BalanceAssets. I have 89 classes
and about 160 simple type member fields (mostly of type decimal, the
"leaves" of my "balance tree") from which a balance is "constructed".
This tree like structure is at most 8 levels deep.

Now to fill in the effective date of a balance I need to create the
appropriate class instances for all members in the path to the "leaf"
effectiveDate:

Balance balance = new Balance();
balance.general = new BalanceGeneral();
balance.general.effectiveDate = DateTime.Today();


In the case of some decimal value in the path down to balance assets
this would be:

balance.assets = new BalanceAssets();
balance.assests.stocks = new BalanceAssetsStocks();
balance.assests.stocks.subMember1 = new
BalanceAssetsStocksSubMember1();
....
balance.assests.stocks.subMember1.subMember11.subMember111.subMember1111.someValue
= 1000;

What I want to know If there is some "mechanism" so that I can avoid
all those "new" operators. I just do a "deep new" on the top level
class and all other instances for the sub-member fields are created,
too. Now I could code a constructor for my top level class Balance
that would do just this or a constructor for each of the 89 classes.
But as I said, this "bunch of classes" is generated from XMLSchemas.
If there is a future change in one of the schemas I will have to
carefully adapt my contructors. And more worse there are three other
data trees besides "Balance" for which I have to generate classes from
the corresponding XML schemas. So that's why I'm asking if there is
some way to automate this process, so that I can just code:

Balance balance = new Balance(true);  // this is the constructor that
will create all member instances
balance.general.effectiveDate = DateTime.Today();
balance.assests.stocks.subMember1.subMember11.subMember111.subMember1111.someValue
= 1000;

So before I start to code this constructor I wanted to ask some C#
expert if there is another approach that I didn't think of.
Stefan

0
7/29/2007 9:40:06 AM
olympus_mons@gmx.de wrote:
> [...]
> What I want to know If there is some "mechanism" so that I can avoid
> all those "new" operators. I just do a "deep new" on the top level
> class and all other instances for the sub-member fields are created,
> too. 

Well, what's your intent with respect to populating the contained classes?

For contained class instances, you must do _some_ initialization 
explicitly.  There's no automatic way for that to happen.  By default 
the reference to the contained instance is null, and it doesn't get to 
be non-null unless you write some code that does that explicitly.

However, if you have some reasonable natural way to instantiate the 
top-level node, then surely you also have some natural way to 
instantiate the contained nodes, all the way down your containment tree. 
  For example, presumably you aren't instantiating the root node without 
data to use to initialize it.  In the same way, shouldn't you have data 
before you go instantiating the contained nodes?  And if so, wouldn't 
the natural method be to simply go through the data as it exists, 
initializing the relevant data structures as necessary?

I'm a bit confused by what appears to be an intent on your part to 
initialize data structures for which you have no data yet.  While I 
think that I do finally understand the basic scenario you're dealing 
with, it seems to me that the design requirement that the entire 
containment tree be completely populated all at once is unnecessary and 
is overcomplicating the implementation.

 > [...]
> If there is a future change in one of the schemas I will have to
> carefully adapt my contructors.

If there is a future change, won't you have to change all of your code? 
  For example:

And more worse there are three other
> data trees besides "Balance" for which I have to generate classes from
> the corresponding XML schemas. So that's why I'm asking if there is
> some way to automate this process, so that I can just code:
> 
> Balance balance = new Balance(true);  // this is the constructor that
> will create all member instances
> balance.general.effectiveDate = DateTime.Today();
> balance.assests.stocks.subMember1.subMember11.subMember111.subMember1111.someValue
> = 1000;

The code above depends on the containment tree.  If the schema changes, 
that will presumably change the fields within the Balance class, 
requiring you to change any code that refers to them.  Thus, any code 
referring to the properties "general" and "assets" needs to be changed 
to address that change.

Basically, any change that would require some manual change to the way 
contained members are initialized will also require some manual change 
to the way they are accessed, and vice a versa.  Trying to automatically 
instantiate the entire tree with empty instances is not only likely to 
be bad design, it's also solving a fairly minimal part of the overall 
problem.

Pete
0
7/29/2007 7:34:20 PM
Pete,

thanks for taking time and sharing your thoughts.

The data comes from a database and needs to be filled into the data
structure. Then the data is serialized to XML and send to a web
service. The data structure in the database is "flat, although I have
created a key table that contains information about parent/child
relationship for balance elements. It also contains XMLSchema element
names and types (these correspond to C# class and property names). I
did this just for informational purposes but now I used this to
generate C# code for my "deep" constructor. The whole process is to
some degree automated by SQL queries that result in C# code. So now I
can create my data structure classes using XSD.EXE and add a "deep"
constructor. The amount of manually coding all this is minimized to a
bit of copy & paste. My solution is now ready to be apllied to the
other XMLschema objects. The C# code that loops through the balance
data and fills in the "flat" data into the data tree is also
generated. Thus any change in the XMLSchema can quickly be turned into
new code.

I don't know if this is really the best solution but it works for me.

Stefan

0
7/29/2007 9:52:49 PM
If you have a 8-level hierarchy tree, i think you'd better consider
more on your design. Inheritance is one of the core features of the OO
Language, but not recommended.

olympus_m...@gmx.de wrote:
> Hi,
>
> I generated C# classes from some complex XMLSchemas usind xsd.exe. The
> result is that I get a class hierarchy that is quite deep (well for me
> 8 levels are deep). What I'm curiuos about is, that if I create an
> instance of my top level element I still need to create instances of
> all sub-elements. What would be the best way to do some sort of "deep
> new" operator, that recursively creates instances for all sub-classes
> (the complete structure consists of 89 different classes).
>
> Lets say my class structure is like
> Top
> +-->Sub1
>       +-->Sub1_1
>       +-->Sub1_2
> +-->Sub2
>       +-->Sub2_1
>       +-->Sub2_2
>
> and instead of:
> Top top = new Top();
> top.sub1 = new Sub1();
> top.sub1.sub1_1 = new Sub1_1();
> top.sub1.sub1_2 = new Sub1_2();
> ...
>
> just do:
> Top top = new Top(true);
>
> which will create instances for all sub-elements.
>
> Of couse I could code a creator method that just does this. But maybe
> this is not the best approach. So what would a experienced C#-guy do?
> Any idea?
>
> Thanks,
> Stefan
>
> P.S.: You probably noticed that I must be new to C#/FW2.0...

0
Garfilone (1)
7/30/2007 12:30:58 AM
Garfilone,

again, this is not a class hierarchy based on inheritance, it's a data
hierarchy based on a bunch of classes. As these classes are generated
from an XMLSchema using XSD.EXE I have no influence on the desgin.
Also I think this quite normal with XMLSchema based data structures.

Stefan

0
8/5/2007 7:37:24 PM
Reply:

Similar Artilces:

Must buy new computer...Ideas?
Hello to all! Finally my over 10-1/2 year old Dell desktop's extreme slowness has seriously gotten on my nerves and I'm now looking for a new one. (Surprisingly, it's working pretty well otherwise...) Maybe this isn't the right forum? But beside the usual things like RAM and HD GBs, are there things I should be sure to have...or be careful NOT to have on a desktop? After n ot looking into computers for over a decade I feel like a Martian in the Earth. lol! Also, is it possible to transfer to the new one ALL my stuff, including programs, etc.? Do you thin...

Problems using xs:anyAttribute in a base class
I using anyAttribute in a base class and this is causing problems in a derived class. I then use xsd to generate C# classes that serialize and deserialze XML. The following schema is what I'm using: <xs:complexType name="BaseType"> <xs:sequence> <xs:element name="ObjectID" type="xs:integer" /> <xs:element name="Name" type="xs:string" minOccurs="0" maxOccurs="1" /> </xs:sequence> <xs:anyAttribute processContents="strict" /> </xs:complexT...

Default properties for new folders
How does one set the default properties applied when creating new email folders? Currently, when I create a new folder, it is created with the AutoPreview turned on by default. I'd like to change that do that it is left off by default. It's something of a pain to create a new folder and then go in to customize it's properties. You can do this by editing the Messages view; View-> Arrange By-> Current View-> Define Views... You might want to define a new view yourself and apply that view on first use of that folder. -- Robert Sparnaaij [MVP-Outlook] www.howto-o...

New Email Messages
I just installed Outlook 2007 on my new PC and for some reason the new messages I received can only be received when I press the SEND/RECEIVE BUTTON. My Outlook at work receives these new mail messages as they are received. So how can I configure the system to make that happen? -- The Trail Hiker!! There are two settings within the accounts 1) Send on starting 2) Auto send/receive every xx minutes - set this for 10 minutes "hiker0531" <hiker0531@aol.com> wrote in message news:87259C7A-5C07-4846-BF61-DE3F98345D21@microsoft.com... >I just installed Outlook 2007 on my n...

error LNK2001 using Winsock in a class
*VC++ 6.0 *command line application using MFC I would like to use the Winsock API functions in a simple class ("CComm"). Example Program: #include <winsock2.h> //#include <winsock.h> CComm::CComm() { // Initialize Winsock. WSADATA wsaData; m_dwErr = WSAStartup(MAKEWORD(2,2), &wsaData); } The linker returns the following error when including "winsock2.h": Comm.obj : error LNK2001: unresolved external symbol __imp__WSAStartup@8 or when including "winsock.h" instead of "winsock2.h": Comm.obj : error LNK2001: unresolved externa...

Prevent new comments on old posts in sharepoint blogs
How do I stop comments on certain posts in a SharePoint blog? I have removed permissions to the specific post to the lowest possible access and people can STILL post a comment. If I uncheck one more item in the list of permissions, the users can no longer see the post. Any suggestions? ...

Unable to open "New" window to write email.
I am using Microsoft Outlook in Office 2003. It has been working great until today. When I click "New" to write a new email I get an error window : The messaging interface has returned an unknown error. If the problem persist, Restart Outlook. I have tried this several times, even restarted the computer to no avail. Anyone have a solution???? ...

New Location/New setup
Currently I'm downsizing our office, and moving to a new location. I'm running MS Server2003 as well as Exchange 2003. Once moved, I will no longer require the server (since I am setting up a home office). Are there currently any steps or procedures available to correctly shutdown one office...and basically setup a home office with no exchange server. Also I will be removing the current pc's from the Domain, and setting up a few in a workgroup. I would like to receive emails from the other employees for time being until I completely cancel this email account. I already have a...

A Short Video on Adding/Editing New Customers
If capturing customers at the POS is important to you, take a couple of minutes and watch this video. This application also allows for edit of Global customer information in HQ installations. http://www.retail-pos.com/ReverseLookup.wmv Contact us for detailed info and demo. sales(at)retail-pos.com www.retail-pos.com It would be nice if you could encode the videos with a more common codec, and not in wmv format. This requires the GTM3 codec (GoToMeeting). Windows Media Player 11 doesn't automatically download the codec, and I'm not going through the trouble to download and in...

How do I activate the new mail button
When I start Outlook, the "New", "forward", "reply" and "reply to all" buttons are not active which means I can not send mail. I have no problems receiving mail. Also, on web pages with email links, when I click on them, the Outlook application is not launched which is almost certainly related to this. I think I'm missing something very simple here! Are you in a mail enabled folder? Do you have an active email account installed? --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. Due to the (insert...

Style available all sheets new or old
I need a custom style that is available in all spreadsheets, new or old. I can set style and save it in book.xlt in xlstart, but that only works for new workbooks, and doesn't work with old spreadsheets when I call them up. I want to be able to select a group of cells, or column or row and apply a setting for negative numbers to have brackets. I am using Excel 2000. I even tried saving the style in personal.xls, but that doesn't work as it is hidden. Do I have to use a macro? And if so what would it be? Thanks One way: Public Sub MergeStyles() ActiveWorkbook....

Sub Form Assigning New Values to Old Records
I am using a subform within a form to have users update certain fields in the record where the rest remiain locked. On the Main form when the list box (which is bound to a query) is used to select the record set to display in the subform it sometimes takes an old record and assigns a new value to the record. For example it changes the Period field from 9 to 10. Taking a record created in period 9 and assigning a period ten to it which is the selection I make in the list box. Addtionally, it looks like it is taking the first record in the related table to assign this new value to. ...

Adding new pages
Any thing I do on new pages happens simultaneously on any previous page. Can someone help me please? Can you be more specific? What stencils are you using and what are you trying? John... Visio MVP Need stencils or ideas? http://www.mvps.org/visio/3rdparty.htm Need VBA examples? http://www.mvps.org/visio/VBA.htm Common Visio Questions http://www.mvps.org/visio/common_questions.htm "Joanie" <anonymous@discussions.microsoft.com> wrote in message news:4C3642E4-4F2B-4A65-8C00-E9041CE74A37@microsoft.com... > Any thing I do on new pages happens simultaneously on any previ...

Which table will refresh by adding new Account / Contact
Hi, I am new to CRM and trying to update CRM Accounts and Contacts from our Sales Management system. I am using Micorosft Bulk Import utility. I am in preparation of CVS files but not sure what columns do I need in CVS file to complete one Account/Contact record. Could anybody please help. I am .NET expert developer, please let me guide If I could develop CRM by using .NET not CVS Regards Hi Adnan, Microsoft do provide CRM SDK for CRM enhancment using .net. You can download from following url http://www.microsoft.com/downloads/details.aspx?familyid=9C178B68-3A06-4898-BC83-BD14B74308C5...

New messages comes up in Deleted folder
Sometimes when I receive new messages the go to the Deleted folder instead of the Inbox. The messages are from random people...not just one sender. What is the problem? Thanks Check your message rules/filters. "key word" in new mail subject line of body is probably being tagged and filtered to deleted items folder. Regards C. >-----Original Message----- >Sometimes when I receive new messages the go to the >Deleted folder instead of the Inbox. The messages are >from random people...not just one sender. What is the >problem? Thanks >. > ...

New User has admin rights
I just created a new user and assigned her the role of Sales Manager. This role is working correctly for other users with it assigned, but she has admin rights? This is the only role she has assigned.... Any ideas? TIA Metcalf ...

New trend, new business, new year a new beginning
New trend, at start of new year. "If you want things to work different, you must try a different...whatever..." Does that seem obvious? Brighten up with this "reading" and attack the money issue with more gusto! I am finishing my year 2005 with some regrets and some joy. For some the year passed has not been "tip top" in their view. But I believe it has just been very well as the page I shall bring you that has this statement which I believe wholeheartedly: "THINGS ARE UNFOLDING AS IT SHOULD" (paraphrased) I invite you to read the whole "poem&quo...

Creating new row in other table
Dear All, Please teach me, how to make a new row/list in other table by entering number in other table. Sample, In the table A and in the field "Details", I put the number 2 and it automatically creates two rows in table B. Can this be done in MS Access? Thank you for your help. Regards, Maulwy Why? What business need are you attempting to solve with this approach? It's generally considered not very good database design to be creating 'empty' rows in a second table. Why do you want empty rows? And if the number you enter in TableA is a 'limit&...

AP
What would be the best tool to add a new field in the AP invoice screen to deploy to a client? Extender? Modifier? the ideal would be to add a field for "Job No." that is text info so the user can get some info out on certain jobs that they are paying bills for. thanks -- Linda W. Linda, You can use any tool, really, to accomplish this: - Modifier with VBA. You can add the fields to the window with Modifier, then use VBA and ADO or DUOS to store and retrieve the data. - Modifier with Dexterity. You can add the fields with Modifier, then trigger off the form with Dex...

Button "New Account" in Sub-Accountsview opens Parent account
When I open an account, and then go to the subaccounts of that account, I click on the Button "New Account" to create a new subaccount for this account. Instead of opening a new account form, the application opens the original Account form. Anybody an idea how this is possible? Regards, Sanne groenhof -- MSCRM, hosted as ASP, and configured for your business. Sanne, Have you installed any specific toolbars in your Internet Explorer? Like google toolbar/msn toolbar? -- Rob Bakkers, Avanade Netherlands "Sanne" wrote: > When I open an account, and then go to...

new to old
hi, A web designing company has just done us a website, and part of it includes the database of our stock. They have written/created it on access xp, but we have only got and old version of access. Can we open/use/update files written in access xp on an older version of access? thanks very much jethro Hi Jethro, It depends. By default Access 2002 (XP) uses the Access 2000 file format, so if you have Access 2000 you may be able to use the database as is. However, if the database is in the form of an mde file created by Access 2002 it will be in Access 2002 format. Otherwise (i.e. if t...

New Accounts on Exchange 2003
This week I entered two new people and the reciepent policy is not providing the necessary email addresses. Of course without those, the GAL does not get updated and no one can email them. I have Exchange 2003 running on Server 2003 with a w2k AD. Any suggestions for jump starting the default reciepent policy? Omer, Thanks for the response. The Recipient Update Service was scheduled for once an hour. I changed it to every 15 minutes. I also tried the "Update Now" feature. For both of these, there were no events generated. I remember setting up trace logs earlier this y...

new columns created from "&nbsp;"
I have a bunch of data in a column and it is "separated" by "&nbsp;". The data was imported from an online database. Is there a way to create columns within the current workbook from where the &nbsp; appears? (much like importing a text file) TIA, Greg Greg Wilker wrote: > I have a bunch of data in a column and it is "separated" by "&nbsp;". > > The data was imported from an online database. > > Is there a way to create columns within the current workbook from where the > &nbsp; appears? (much like importing a te...

create new folder is always greyed out-why?
"Create new folder" is always greyed out-why? ...

No new fonts allowed
I have an excel workbook that contains graphs, downloads and linked data and I consistantly get an error when updating the spreadsheet and graphs - "No more new Fonts may be applied to this workbook". What is this error telling me? What can and can I not do? Has anyone else experienced this? Jon Peltier has some information on this in his Charting FAQ article: http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=209#jon025 david wrote: > I have an excel workbook that contains graphs, downloads > and linked data and I consistantly get an error when > updat...