none
How to assign different object types RRS feed

  • Question

  • I have two classes A and B. Both HAVE SAME FIELDS..Is there any way to copy an object of A to an object of B without copying field by field. That is

    A obj1;

    obj1.a = 1;

    obj1.b = 2;

    obj1.c = 3;

    Instead of 

    B obj2;

    obj2.a = obj1.a;

    obj2.b = obj1.b;

    obj2.c = obj1.c;

    I would like something which allows me the above operation in a single step like:

    Copy(obj2, obj1);     Or similar


    • Edited by SQLNeophyte Tuesday, March 19, 2019 1:06 PM
    Tuesday, March 19, 2019 1:00 PM

Answers

  • Hi

    Thank you for posting here.

    According to your description, you want to copy an object of A to an object of B without copying field by field.

    You could use reflection to get it, please try the following code.

    class Program
        {
            public class A
            {
                public string name { get; set; }
                public int Age { get; set; }
            }
            public class B
            {
                public string name { get; set; }
                public int Age { get; set; }
            }
    
            static void Main(string[] args)
            {
                B b = new B();
    
                b.name = "1";
    
                b.Age = 15;
    
                A a = Copy<A, B>(b);
    
                Console.WriteLine(a.Age);
                Console.WriteLine(a.name);
                Console.ReadKey();
            }
            public static D Copy<D, S>(S s)
            {
                D d = Activator.CreateInstance<D>();
                try
                {
                    var sType = s.GetType();
    
                    var dType = typeof(D);
    
                    foreach (PropertyInfo sP in sType.GetProperties())
                    {
                        foreach (PropertyInfo dP in dType.GetProperties())
                        {
    
                            if (dP.Name == sP.Name)
                            {
                                dP.SetValue(d, sP.GetValue(s));
                            }
    
                        }
    
                    }
    
                }
    
                catch (Exception ex)
                {
    
                    Console.WriteLine(ex);
                }
                return d;
            }
    }
    

    Result:

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 20, 2019 6:33 AM
    Moderator

All replies

  • What you're looking for might be a deep copy. So, take a look at this approach: Deep copy of an object

    wizend

    Tuesday, March 19, 2019 1:09 PM
  • Hi Wizend,

    Can you please post the correct link?

    Tuesday, March 19, 2019 1:41 PM
  • Not in C#. What you're looking for is something language people call structural equivalence. That is the ability to say 2 structures (types) are equivalent (and therefore assignable) if they have the same layout (e.g. fields). Some languages support this but C-based languages like C# do not.

    The only way to do this in C# is to copy each field. You can generically do this using reflection which is how serializers tend to work. But you still have to define some rules around what happens if the fields have compatible but different types, incompatible types, missing fields, etc.

    Note you could also solve this by using a class hierarchy if you control both types A and B but you're still going to have to copy the fields.


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, March 19, 2019 1:46 PM
    Moderator
  • After reading the answer of Michael Taylor I realized that your question is about two "different" classes and not about two different objects of one class. So, a deep copy of an object won't help you.

    wizend

    Tuesday, March 19, 2019 3:51 PM
  • I have two classes A and B. Both HAVE SAME FIELDS..Is there any way to copy an object of A to an object of B without copying field by field. by 

    If the classes/objects are using the same public properties, then you can copy data by publc properties across objects.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

    You can use Automapper to map  object data to another object by their properties.

    https://www.c-sharpcorner.com/article/getting-started-with-automapper/

    Tuesday, March 19, 2019 4:55 PM
  • Hi

    Thank you for posting here.

    According to your description, you want to copy an object of A to an object of B without copying field by field.

    You could use reflection to get it, please try the following code.

    class Program
        {
            public class A
            {
                public string name { get; set; }
                public int Age { get; set; }
            }
            public class B
            {
                public string name { get; set; }
                public int Age { get; set; }
            }
    
            static void Main(string[] args)
            {
                B b = new B();
    
                b.name = "1";
    
                b.Age = 15;
    
                A a = Copy<A, B>(b);
    
                Console.WriteLine(a.Age);
                Console.WriteLine(a.name);
                Console.ReadKey();
            }
            public static D Copy<D, S>(S s)
            {
                D d = Activator.CreateInstance<D>();
                try
                {
                    var sType = s.GetType();
    
                    var dType = typeof(D);
    
                    foreach (PropertyInfo sP in sType.GetProperties())
                    {
                        foreach (PropertyInfo dP in dType.GetProperties())
                        {
    
                            if (dP.Name == sP.Name)
                            {
                                dP.SetValue(d, sP.GetValue(s));
                            }
    
                        }
    
                    }
    
                }
    
                catch (Exception ex)
                {
    
                    Console.WriteLine(ex);
                }
                return d;
            }
    }
    

    Result:

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 20, 2019 6:33 AM
    Moderator