Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Is there any technique available for copying one object of class A to another object of class B ?

Is there any technique available for copying one object of class A to another object of class B ?

Scheduled Pinned Locked Moved C#
tutorialquestion
13 Posts 7 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Nadia Monalisa

    Hi, Thanks for your reply. Actually, my classes are auto generated and I dont have control over them. I mean, my class A is a LINQ to SQL model generated from the dbml file, and class B is a proxy class for a WCF Service. Yeah, I can manipulate those classes manually but it will be hard to maintain when I will update my service reference or dbml file. So, I was looking for some other technique that can take an object of class A and return object of class B where all properties of A is copied to B.

    N Offline
    N Offline
    nlarson11
    wrote on last edited by
    #4

    ah. i would just use reflection then. get all the properites available from class A and then go through all the properties of class B. if there is a match then copy the data from A to B.

    'Never argue with an idiot; they'll drag you down to their level and beat you with experience.' ~ anonymous

    N 1 Reply Last reply
    0
    • N nlarson11

      ah. i would just use reflection then. get all the properites available from class A and then go through all the properties of class B. if there is a match then copy the data from A to B.

      'Never argue with an idiot; they'll drag you down to their level and beat you with experience.' ~ anonymous

      N Offline
      N Offline
      Nadia Monalisa
      wrote on last edited by
      #5

      Thanks again. I am not familiar with Reflection. Would you please give me any example snippet Or point me to an article which shows how to do this task as you mentioned ?

      N 1 Reply Last reply
      0
      • N Nadia Monalisa

        Thanks again. I am not familiar with Reflection. Would you please give me any example snippet Or point me to an article which shows how to do this task as you mentioned ?

        N Offline
        N Offline
        nlarson11
        wrote on last edited by
        #6

        Forgive...i'm a lowly VB programmer and i just quickly threw this together - so translate it and it should do what your looking for

        Imports System.Reflection

        Public Class Form1
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim a As New TheFromClass With {.Hello = "hello there", .Name = "myclass"}
        Dim b As New TheToClass With {.GoodBye = "later dude", .Hello = "wuzup"}

            Dim ta As Type = GetType(TheFromClass)
            Dim tb As Type = GetType(TheToClass)
        
            Dim obj As Object, PropertyName As String, ToPI As PropertyInfo = Nothing
        
            MsgBox(b.Hello)
        
            For Each FromPI As PropertyInfo In ta.GetProperties
                PropertyName = FromPI.Name
                obj = FromPI.GetValue(a, Nothing)
        
                ToPI = tb.GetProperties.Where(Function(p) p.Name = PropertyName).FirstOrDefault
        
                If ToPI IsNot Nothing Then ToPI.SetValue(b, obj, Nothing)
            Next
        
            MsgBox(b.Hello)
        
            End
        End Sub
        

        End Class

        Public Class TheFromClass
        Public Property Hello As String
        Public Property Name As String
        End Class

        Public Class TheToClass
        Public Property GoodBye As String
        Public Property Hello As String
        End Class

        'Never argue with an idiot; they'll drag you down to their level and beat you with experience.' ~ anonymous

        N 1 Reply Last reply
        0
        • N nlarson11

          Forgive...i'm a lowly VB programmer and i just quickly threw this together - so translate it and it should do what your looking for

          Imports System.Reflection

          Public Class Form1
          Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
          Dim a As New TheFromClass With {.Hello = "hello there", .Name = "myclass"}
          Dim b As New TheToClass With {.GoodBye = "later dude", .Hello = "wuzup"}

              Dim ta As Type = GetType(TheFromClass)
              Dim tb As Type = GetType(TheToClass)
          
              Dim obj As Object, PropertyName As String, ToPI As PropertyInfo = Nothing
          
              MsgBox(b.Hello)
          
              For Each FromPI As PropertyInfo In ta.GetProperties
                  PropertyName = FromPI.Name
                  obj = FromPI.GetValue(a, Nothing)
          
                  ToPI = tb.GetProperties.Where(Function(p) p.Name = PropertyName).FirstOrDefault
          
                  If ToPI IsNot Nothing Then ToPI.SetValue(b, obj, Nothing)
              Next
          
              MsgBox(b.Hello)
          
              End
          End Sub
          

          End Class

          Public Class TheFromClass
          Public Property Hello As String
          Public Property Name As String
          End Class

          Public Class TheToClass
          Public Property GoodBye As String
          Public Property Hello As String
          End Class

          'Never argue with an idiot; they'll drag you down to their level and beat you with experience.' ~ anonymous

          N Offline
          N Offline
          Nadia Monalisa
          wrote on last edited by
          #7

          Thanks a loooooooooooooot. I highly appreciate. Yes, I know some online VB to C# converter, so this code will be fine. :) Regards.

          1 Reply Last reply
          0
          • N Nadia Monalisa

            Hi, I am wondering, is there any technique available to copy an object to another object when the objects are of different class but the signature of these classes are same (100% identical) ? For example, if I have

            class A
            {
            public string Name;
            public string EmailAddress;
            }

            and

            class B
            {
            public string Name;
            public string EmailAddress;
            }

            Now, in my code, I have a::A, b::B. I want to copy all property values from b to a, but I have to do it manually by iterating all properties of b to a one by one like this.

            a.Name = b.Name;
            a.EmailAddress = b.EmailAddress;

            I wish if there were any techniq to automate this task!! I know about Copy/Cloning techniques where the objects are from same class. But as you see my objects are from different class. If my class were so simply like this, I would not have worried, but my class A and B has around 50 properties which is hard to maintain. So, I would appreciate any idea. Regards.

            G Offline
            G Offline
            Giorgi Dalakishvili
            wrote on last edited by
            #8

            You can use Binary Serialization[^]

            Giorgi Dalakishvili #region signature My Articles Browsing xkcd in a windows 7 way[^] #endregion

            1 Reply Last reply
            0
            • N Nadia Monalisa

              Hi, I am wondering, is there any technique available to copy an object to another object when the objects are of different class but the signature of these classes are same (100% identical) ? For example, if I have

              class A
              {
              public string Name;
              public string EmailAddress;
              }

              and

              class B
              {
              public string Name;
              public string EmailAddress;
              }

              Now, in my code, I have a::A, b::B. I want to copy all property values from b to a, but I have to do it manually by iterating all properties of b to a one by one like this.

              a.Name = b.Name;
              a.EmailAddress = b.EmailAddress;

              I wish if there were any techniq to automate this task!! I know about Copy/Cloning techniques where the objects are from same class. But as you see my objects are from different class. If my class were so simply like this, I would not have worried, but my class A and B has around 50 properties which is hard to maintain. So, I would appreciate any idea. Regards.

              B Offline
              B Offline
              Bernhard Hiller
              wrote on last edited by
              #9

              Try this:

                  public static void CopyFields(object source, object target)
                  {
                      if (source == null)
                          throw new ArgumentNullException("source");
                      if (target == null)
                          throw new ArgumentNullException("target");
              
                      //loop through source object
                      FieldInfo\[\] fiSource = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                      FieldInfo\[\] fiTarget = target.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                      foreach (FieldInfo fiS in fiSource)
                      {
                          //check if that field exists in target
                          foreach (FieldInfo fiT in fiTarget)
                          {
                              if (fiT.Name == fiS.Name)
                              {
                                  //copy value
                                  fiT.SetValue(target, fiS.GetValue(source));
                                  //stop inner loop
                                  break;
                              }
                          }
                      }
                  }
              

              Then call CopyFields(a, b).

              N P I 3 Replies Last reply
              0
              • B Bernhard Hiller

                Try this:

                    public static void CopyFields(object source, object target)
                    {
                        if (source == null)
                            throw new ArgumentNullException("source");
                        if (target == null)
                            throw new ArgumentNullException("target");
                
                        //loop through source object
                        FieldInfo\[\] fiSource = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        FieldInfo\[\] fiTarget = target.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        foreach (FieldInfo fiS in fiSource)
                        {
                            //check if that field exists in target
                            foreach (FieldInfo fiT in fiTarget)
                            {
                                if (fiT.Name == fiS.Name)
                                {
                                    //copy value
                                    fiT.SetValue(target, fiS.GetValue(source));
                                    //stop inner loop
                                    break;
                                }
                            }
                        }
                    }
                

                Then call CopyFields(a, b).

                N Offline
                N Offline
                Nadia Monalisa
                wrote on last edited by
                #10

                Hi Bhiller, Thank you soooo much.. Your code will be highly useful for me. I just checked your code and awesome!! Great !! Thats the solution what I was searching for so loooong time. Many many thanks.

                modified on Friday, August 6, 2010 2:49 AM

                1 Reply Last reply
                0
                • N Nadia Monalisa

                  Hi, I am wondering, is there any technique available to copy an object to another object when the objects are of different class but the signature of these classes are same (100% identical) ? For example, if I have

                  class A
                  {
                  public string Name;
                  public string EmailAddress;
                  }

                  and

                  class B
                  {
                  public string Name;
                  public string EmailAddress;
                  }

                  Now, in my code, I have a::A, b::B. I want to copy all property values from b to a, but I have to do it manually by iterating all properties of b to a one by one like this.

                  a.Name = b.Name;
                  a.EmailAddress = b.EmailAddress;

                  I wish if there were any techniq to automate this task!! I know about Copy/Cloning techniques where the objects are from same class. But as you see my objects are from different class. If my class were so simply like this, I would not have worried, but my class A and B has around 50 properties which is hard to maintain. So, I would appreciate any idea. Regards.

                  L Offline
                  L Offline
                  Lukasz Nowakowski
                  wrote on last edited by
                  #11

                  I don't know how it works for LINQ to SQL model, but once I did something like this for Entity Framework model. For web application there was supposed to be a WCF server, that was interacting with database with help of EF. And web application wasn't supposed to reference EF libraries (cause there should be separation) and I had to do mapping between EF classes an POCO classes. And to do it I used tt scripts. They are used to generate files (different kinds of them). And with those scripts I also created some mapper, that created mappings for each class defined in the model. Maybe you can find something like this for LINQ to SQL (unfortunately I don't have time to search for it, and looking at TODO list wan't have in the nearest future).

                  Don't forget to rate answer, that helped you. It will allow other people find their answers faster.

                  1 Reply Last reply
                  0
                  • B Bernhard Hiller

                    Try this:

                        public static void CopyFields(object source, object target)
                        {
                            if (source == null)
                                throw new ArgumentNullException("source");
                            if (target == null)
                                throw new ArgumentNullException("target");
                    
                            //loop through source object
                            FieldInfo\[\] fiSource = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                            FieldInfo\[\] fiTarget = target.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                            foreach (FieldInfo fiS in fiSource)
                            {
                                //check if that field exists in target
                                foreach (FieldInfo fiT in fiTarget)
                                {
                                    if (fiT.Name == fiS.Name)
                                    {
                                        //copy value
                                        fiT.SetValue(target, fiS.GetValue(source));
                                        //stop inner loop
                                        break;
                                    }
                                }
                            }
                        }
                    

                    Then call CopyFields(a, b).

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #12

                    I would cache the information to make repeated calls quicker.

                    1 Reply Last reply
                    0
                    • B Bernhard Hiller

                      Try this:

                          public static void CopyFields(object source, object target)
                          {
                              if (source == null)
                                  throw new ArgumentNullException("source");
                              if (target == null)
                                  throw new ArgumentNullException("target");
                      
                              //loop through source object
                              FieldInfo\[\] fiSource = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                              FieldInfo\[\] fiTarget = target.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                              foreach (FieldInfo fiS in fiSource)
                              {
                                  //check if that field exists in target
                                  foreach (FieldInfo fiT in fiTarget)
                                  {
                                      if (fiT.Name == fiS.Name)
                                      {
                                          //copy value
                                          fiT.SetValue(target, fiS.GetValue(source));
                                          //stop inner loop
                                          break;
                                      }
                                  }
                              }
                          }
                      

                      Then call CopyFields(a, b).

                      I Offline
                      I Offline
                      il_manti
                      wrote on last edited by
                      #13

                      Hi, This is looking great. Quick question, is there any way to modify this code to allow for inner class conversions too? My classes have inner classes and these too differ by name space. I have no idea how reflection works so if you could be kind enough to point out a solution for me it would be great. If not, I'll try to figure it out :/ Thanks a lot for your time.

                      In life truth does not matter. What really matters is what others believe to be the truth. (The Up and Comer - Book)

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups