473,728 Members | 1,623 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to implement a C# copy constructor

I want to copy a parent class instance's all datas to a child's. It's
actually a C++'s copy constructor. But why the following code does not
work - there is a compile error! How it should look like?

(The background is I don't know (I don't care indeed) all members in
DataGrid, so I don't want to copy all members in DataGrid one by one.)

public class GridEx : DataGrid
{
public GridEx()
{
InitializeCompo nent();
this.HeaderClic ked += new HeaderEventHand ler(
InternalHeaderC lick );
}

public GridEx( DataGrid src )
: this()
{
base = src.MemberwiseC lone(); //error CS0175: Use of keyword base
is not valid in this context
// Why? and how
should I to do??????????
// OR
this = src.MemberwiseC lone(); //error CS1540: Cannot access
protected member
//'object.Memberw iseClone()'
via a qualifier of type 'DataGrid';
//the qualifier must be of
type 'GridEx' (or derived from it)

// What's the solution for the issue?????????? ?????
}
}

Nov 15 '05 #1
4 17194
Peter wrote:
base = src.MemberwiseC lone(); //error CS0175: Use of
keyword base is not valid in this context
// Why?
base is a keyword indicating the invocation of a member belonging to a
type's base class. Use a different variable name.
this = src.MemberwiseC lone(); //error CS1540: Cannot
access protected member

//'object.Memberw iseClone()' via a qualifier of type 'DataGrid';
//the qualifier must
be of type 'GridEx' (or derived from it)

// What's the solution for the issue?????????? ?????


According to the code, you're trying to define a conversion operator not a
copy constructor.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
Nov 15 '05 #2

"Peter" <ab*@hotmail.co m> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
I want to copy a parent class instance's all datas to a child's. It's
actually a C++'s copy constructor. But why the following code does not
work - there is a compile error! How it should look like?

(The background is I don't know (I don't care indeed) all members in
DataGrid, so I don't want to copy all members in DataGrid one by one.)

public class GridEx : DataGrid
{
public GridEx()
{
InitializeCompo nent();
this.HeaderClic ked += new HeaderEventHand ler(
InternalHeaderC lick );
}

public GridEx( DataGrid src )
: this()
{
base = src.MemberwiseC lone(); //error CS0175: Use of keyword base
is not valid in this context
// Why? and how
should I to do??????????
// OR
this = src.MemberwiseC lone(); //error CS1540: Cannot access
protected member

//'object.Memberw iseClone()'
via a qualifier of type 'DataGrid';
//the qualifier must be of
type 'GridEx' (or derived from it)

// What's the solution for the issue?????????? ?????
}
}
As a whole, the copy constructor pattern doesn't work as it does in C++. You
are better off using ICloneable and the .Clone() method instead of trying to
make copy constructors work.

public class MyClass : ICloneable

{

public object Clone()

{

return this.Memberwise Clone();

}

}

Nov 15 '05 #3

Hi Peter,

Thank you for posting in the community!

Based on my understanding, you want to implement an extended datagrid in
C#, and you want to initialize your extended datagrid with an existed
normal datagrid instance.
=============== =============== ============
In your description "copy a parent class instance's all datas to a
child's", what exactly does "all data" mean? Does it mean "Shadow Copy" or
"Deep Copy"?

To see the difference between "Shadow Copy" and "Deep Copy", please refer
to "Remarks" section in below link:
http://msdn.microsoft.com/library/de...us/cpref/html/
frlrfsystemobje ctclassmemberwi seclonetopic.as p

Based on your code snippet, I think you want to implement "Shadow
Copy"(Because you use MemberwiseClone method)

Because MemberwiseClone is a protected member of object class, you can not
call it outside of this class or its child class. (That's why the error
message generates)

Just as Daniel said, to do clone in .Net, you may implement the ICloneable
interface, this interface only takes one method "Clone", which you can do
your copy implement. Normally, to do Shadow Copy, you can just call the
object.Memberwi seClone in the interface's implement.
In "ICloneable Interface" below, you will see that, DataGrid class does not
implement ICloneable interface, so you must implement this interface
yourself:
http://msdn.microsoft.com/library/de...us/cpref/html/
frlrfsystemiclo neableclasstopi c.asp

As a whole, you should do like this:
public class MyDataGrid : ICloneable, DataGrid
{
public object Clone()
{
return this.Memberwise Clone();
}
}

public class extendeddatagri d: DataGrid
{
public extendeddatagri d(MyDataGrid obj)
{
this=obj.Clone( ) as DataGrid;
}
}

Note: in the constructor parameter, you must use the class inherited from
DataGrid, which may not meet your need(You want to take the Normal DataGrid
as parameter), if you really want to use normal DataGrid as parameter, you
must do the Shadow Copy yourself in the constructor, which may be
troublesome.

=============== =============== =============== ====
Please apply my suggestion above and let me know if it helps resolve your
problem.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.
Have a nice day!!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #4

Hi Peter,

Does my reply make sense to you?

If you still have anything unclear, please feel free to tell me, I will
help you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
5792
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
15
21197
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including pointers) and for objects types call their default constructor. Any others points i should know?
8
20029
by: Jesper | last post by:
Hi, Does the concept "copy constructor" from c++ excist in c#. What is the syntax. best regards Jesper.
10
2574
by: utab | last post by:
Dear all, So passing and returning a class object is the time when to include the definition of the copy constructor into the class definition. But if we don't call by value or return by value, we do not need to use the copy-constructor. So depending on the above reasoning I can avoid call by value and return by value for class objects, this bypasses the problem or it seems to me like that. Could any one give me some simple examples...
8
4297
by: shuisheng | last post by:
Dear All, I am wondering how the default copy constructor of a derived class looks like. Does it look like class B : public A { B(const B& right) : A(right) {}
4
3145
by: shuisheng | last post by:
Dear All, Is there any easy way to make sure all my object copies are deep copy or shallow copy? I do not like to implement it in each class one by one. Thanks, Shuisheng
22
3619
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float v);
2
2338
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include "Queuep.h" #include <cassert> #include <new> using namespace std; Queue::Queue () : backPtr (0), frontPtr(0) { }
2
2930
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include <cassert // for assert #include <new // for bad_alloc using namespace std; //private:{Queue::Queue(const Queue& Q)}
0
8899
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8757
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9418
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9272
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9196
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6712
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4524
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3235
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2651
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.