-3

What's an easy way to cast one object to another when they have the same properties? For example:

public class Test1
{
   public string FirstName{ get; set; }
   public string LastName{ get; set; }
}

public class Test2
{
   public string FirstName{ get; set; }
   public string LastName{ get; set; }
}

So if I have a populated Test1 object and I want all of its values to be populated into Test2, then what's the easiest way to do that? I know I can set values 1-by-1 from Test1 to Test2 but I was wondering if you could recommend a quicker, easier way? Like test1.Map(test2) or something like that?

user8570495
  • 1,645
  • 5
  • 19
  • 29

1 Answers1

0

If one can be inherited from the other:

public class Test1 {
   public string FirstName{ get; set; }
   public string LastName { get; set; }
}

public class Test2 : Test1 { }

then simple cast :

Test2 test2 = new Test2 { FirstName = "A", LastName = "B" };
Test1 test1 = test2;                                         // or var test1 = (Test1)test2;
Slai
  • 22,144
  • 5
  • 45
  • 53