Geeks With Blogs

Michael Freidgeim's Blog MS .Net Development

I have a base class with a lot of data members and I wanted to create a constructor in derived class, that will take a base class as a parameter and assign all data members values from the parameter:

class Derived: Base
{
    Derived(Base baseClass)
   {
      //Assign all data
    }
}

The function is almost like  Copy Constructor, so I tried to search Google for it.
There is a discussion on MBR IT/.NET 247 : how to implement a C# copy constructor .

where Jeffrey Tan from Microsoft Support suggested :
public extendeddatagrid(MyDataGrid obj)
{
this=obj.Clone() as DataGrid;
}

Unfortunately, it is not allowed to assign object to this in .Net.
I’ve also found a good article on
Windojitsu.com -- Copy Constructors vs ICloneable. 

But .Net framework doesn’t have a facility to assign all members like MemberwiseClone Method does for copying.

So developer has to write code to assign all data members from passed object. It is quite annoying for big classes like I have.

The related topisc are discussed in article Copying, Cloning, and Marshalling in .NET

Update: See my post Implement Copy constructor using Serialization or Reflecton

Posted on Friday, May 25, 2007 12:46 PM | Back to top


Comments on this post: No Copy Constructor support in .Net framework.

# re: No Copy Constructor support in .Net framework.
Requesting Gravatar...
Why not use reflection?

Like this:
http://geekswithblogs.net/thibbard/archive/2007/05/04/Architecture-thoughts-and-Reflection.aspx
Left by Tim Hibbard on May 25, 2007 1:40 PM

# re: No Copy Constructor support in .Net framework.
Requesting Gravatar...
Thanks, Tim.
To use reflection is a good idea. It has some performance penalties, but in most cases they are minor. Your approach could save a lot of development/code maintenance time.
Left by Michael Freidgeim on May 27, 2007 2:12 AM

# re: No Copy Constructor support in .Net framework.
Requesting Gravatar...
I agree reflection would be more useful in this case
Left by web development company on Aug 19, 2009 1:21 PM

Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net | Join free