March 2008 Archives

Generic C# Object Copy Function

| 1 Comment | No TrackBacks
Hi everyone, sorry I haven't completed writing about my Plugin system, but I did successfully find a solution to my issues, and created a flexible system which works very well.  I'll get more into that later, but I'm very happy with it and am not able to quickly create plugins of different types and use them within my applications.  The database code is so utterly simple [ I wrote 3 different database plugins, for MySQL/SQL Server/MS Access ] to use:




However, that's not what the subject of this article is!  I needed a quick and easy way to copy objects of differing types to one another, as long as they have matching fields.  An example would be a base class, to a derived class of similar type.. but they're different, so you can't just do a direct assignment!  Here is the code:



Usage:
tbl_myTable source = new tbl_myTable();
tbl_myTableDerived dest = new tbl_myTableDerived();
source.name = "Joe";

CopyObject(source, dest);

MessageBox.Show(dest.name); // "Joe";

Only fieldnames that are equal in both classes will be copied.  For thoroughness, it would be better to make sure the types are also equal -- but I don't need to go through the hassle of that, in my scenarios the field types and names will be equal.  YMMV.

Thank you!  I hope someone finds this very useful.

- Matthew MacSuga

About this Archive

This page is an archive of entries from March 2008 listed from newest to oldest.

January 2008 is the previous archive.

April 2008 is the next archive.

Find recent content on the main index or look in the archives to find all content.