Share via


How can I Convert a Class Object to another similar Class Object

Question

Friday, February 5, 2010 3:14 PM

Hi,

I have two similar public classes at different places and at some point, I need to assign all the filled values in one class to same another class. Can I do it by any generalized way other than by assigning each property individually?

Here is my code, just for example,

================================================================================

public class FirstClass
{
    public string TestString1 = "";
    public string TestString2 = "";
}

public class SecondClass
{
    public string TestString1 = "";
    public string TestString2 = "";

}

And I want to do something like,

FirstClass obj1 = new FirstClass();
SecondClass obj2 = new SecondClass();

//obj2 = obj1; -- This is what I want to do but dont know how to convert this

================================================================================

So I have two same classes as above and at one point, I have object of FirstClass and I want to assign it to SecondClass, How can I do it?

All replies (5)

Sunday, February 7, 2010 5:17 AM âś…Answered

You should probably be using an interface or an abstract class. If both FirstClass and SecondClass implement either an interface or inherit from an abstract class then you can use the interface or abstract class as the type definition when declaring the variables obj1 and obj2.

public class ISomeInterface
{
 string TestString1 { get; set; }
 string TestString2 { get; set; }
}

public class FirstClass : ISomeInterface
{
 // implement interface
}

public class SecondClass : ISomeInterface
{
 // implement interface
}

In this situation both FirstClass and SecondClass implement ISomeInterface. Then in your code you could do this:

ISomeInterface obj1 = new FirstClass();
ISomeInterface obj2 = new SecondClass();

obj2 = obj1; // since they are both of the same type

But this method will limit you to only the methods and properties that ISomeInterface declares.


Friday, February 5, 2010 4:05 PM

Well you can just write a method that takes in Class1 and returns Class2 and new's up a Class2 and assigns each of the properties to it.

You can also do something called conversion operator overloading:


Friday, February 5, 2010 5:08 PM

Yes, As I said, I can assign properties one by one but I want to know if its possible to convert the class with the exact same definition class in any generalized way so that I do not have to write each properties. 


Saturday, February 6, 2010 6:03 AM

Yes it is possible to do something with reflection but it will be much slower than coding it by assigning each property.


Saturday, February 6, 2010 6:42 AM

It would be useful if the classes implemented an interface for the common fields.