473,385 Members | 1,311 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Use reflection to copy a class

I have a complicated class that I use to store a lot of values
Now I need a copy of that class and I have been trying to find a way to do
this automatic so I don't have to assign all properties and classes by hand
(about 200 properties).
I found this post on google:
http://www.thescripts.com/forum/thread225825.html
But how does this code work and what do I use instead of "oth" in the last
line
using System.Reflection;
class MyClass {
int a;
// lots of different fields goes here
float x;
MyClass() {
// default constructor
}
MyClass (MyClass my) {
// create an exact copy of mc here
FieldInfo[] fields = typeof(MyClass).GetFields(BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance);
foreach(FieldInfo f in fields) {
f.SetValue(this,f.GetValue(oth));
}
}
}

Thansk Torben
Apr 30 '07 #1
2 2307
On 30 Apr, 10:45, "Torben Laursen" <Tor...@newsgroups.nospamwrote:
I have a complicated class that I use to store a lot of values
Now I need a copy of that class and I have been trying to find a way to do
this automatic so I don't have to assign all properties and classes by hand
(about 200 properties).
I found this post on google:http://www.thescripts.com/forum/thread225825.html
But how does this code work and what do I use instead of "oth" in the last
line
using System.Reflection;
class MyClass {
int a;
// lots of different fields goes here
float x;
MyClass() {
// default constructor}

MyClass (MyClass my) {
// create an exact copy of mc here
FieldInfo[] fields = typeof(MyClass).GetFields(BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance);
foreach(FieldInfo f in fields) {
f.SetValue(this,f.GetValue(oth));

}
}
}

Thansk Torben
All it's doing is iterating through the fields, so GetValue's
parameter is the object we're copying. However, this method won't work
with a derived type.

so if you have

public class Test
{
private int f;
public int F
{
get
{
return f;
}
set
{
f=value;
}
}
}

public class Test2 : Test
{
private int g;
public int G

{
get
{
return g;
}
set
{
g=value;
}
}
}

public Test2 Clone2(Test2 pTest2)
{
Test2 o = new Test2();

FieldInfo[] fields = typeof(Test2).GetFields(BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance);
foreach(FieldInfo f in fields)
{
f.SetValue(o,f.GetValue(pTest2));
}
return o;
}

Cloning a Test2 with his code (mashed up above) will result in g being
set but not f. The following seems to work, but I've not extensively
tested it, so consider it a starting point rather than a solution.
Apologies for the scrappyness of the code :)

public Test2 Clone3(Test2 pTest2)
{
Test2 o = new Test2();
Type t;
FieldInfo[] fields;
t = typeof(Test2).BaseType;
while(t != null)
{
fields = t.GetFields(BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance);
foreach(FieldInfo f in fields)
{
f.SetValue(o,f.GetValue(pTest2));
}
t = t.BaseType;
}

fields = typeof(Test2).GetFields(BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance);
foreach(FieldInfo f in fields)
{
f.SetValue(o,f.GetValue(pTest2));
}
return o;
}
Apr 30 '07 #2
"Torben Laursen" <To****@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
But how does this code work and what do I use instead of "oth" in the last
line
[...]
f.SetValue(this,f.GetValue(oth));
How does it work? You are iterating through all the fields in the class,
reading the values from another instance ("oth") and inserting the values in
your current instance, which will give you a shallow copy of the object,
which is what you wanted in the first place.
What do you use instead of "oth"? Well, the object that you wanted to
copy in the first place, which was the purpose of the whole thing, wasn't
it? I believe that there is an error in the parameters of the constructor.
Where you write MyClass(MyClass my), you should have MyClass(MyClass oth),
so you can pass the object to copy as an argument when you do a "new
MyClass".
Apr 30 '07 #3

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

Similar topics

9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
5
by: Andre | last post by:
I have two questions; 1) When executing the sub routine "TestStructure", I'm trying to update the member "intTyres" in the structure "structureCar" dynamically using System.Reflection. The code...
3
by: Jozsef Bekes | last post by:
Hi All, I am trying to use reflection for getting all the classes from the dlls of a software written by my company. I am using this line: Assembly.LoadFile(s).GetTypes() Gettypes fails, I...
6
by: Joanna Carter \(TeamB\) | last post by:
Hi folks I have a Generic Value Type and I want to detect when the internal value changes. /////////////////////////////// public delegate void ValueTypeValidationHandler<T>(T oldValue, T...
2
by: Wiktor Zychla | last post by:
Let's start with an example: if you have: class Test { public delegate int MyDelegate( int n ); event MyDelegate MyEvent; } then you can get MyEvent using reflection:
1
by: Patrick | last post by:
Has been trying to get an ASP.NET DLL's modification date/time for the "release date/time" to be displayed on the page's footer Using: System.Reflection.Assembly...
5
by: heddy | last post by:
I understand that reflection allows me to discover the metadata of a class at runtime (properties, methods etc). What I don't understand is where this is useful. For example: If I am the sole...
2
by: wizofaus | last post by:
Given the following code: public class Test { static unsafe void StringManip(string data) { fixed (char* ps = data) ps = '$'; }
6
by: Cralis | last post by:
Hi guys, Someone once said, 'You can do that with reflection'. I can't recall what it was I was trying to do at the time, but then he said, 'Any developer knows what reflection is...'. I kept...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.