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:

tbl_myTable source = new tbl_myTable();
tbl_myTableDerived dest = new tbl_myTableDerived(); = "Joe";

CopyObject(source, dest);

MessageBox.Show(; // "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

No TrackBacks

TrackBack URL:

1 Comment

This is really very useful.
Do try this also
Its lil complex way but gr8 use of reflection.

Leave a comment

About this Entry

This page contains a single entry by Matthew M. published on March 18, 2008 7:28 PM.

Overriding Dataset Settings Connection String was the previous entry in this blog.

Asymmetric Key Encryption with RSA and X509 is the next entry in this blog.

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