Sem
Sem

Reputation: 73

Set propperties from an object to another 'similar' object in C#

I have two objects like:

class HOUSE_MODEL
{
   int RoomSize,
   int NumberOfBaths
   int GarageSize  
}

class DB_HOUSE_ENTITY
{
   int RoomSize,
   int NumberOfBaths
   int NumberOfDoors
}

I want Create a HOUSE_MODEL object and copy all values of the DB_HOUSE_ENTITY object if the property have the same name in both objects (in this case i would like copy roomSize and NumberOfBaths properties).

There is anyway to do this without copy one to one properties from one object to the other?

thanks in advance.

Upvotes: 0

Views: 258

Answers (1)

Patrick
Patrick

Reputation: 8318

The traditional way of doing this is to create copy constructors:

public class HouseModel
{
   int RoomSize,
   int NumberOfBaths
   int GarageSize  

   public HouseModel( DbHouseModel model )
   {
       RoomSize = model.RoomSize;
       NumberOfBaths = model.NumberOfBaths; 
   }
}

This has some advantages over mappers, particularly it causes a compile time error if someone changes the name of a member of one of the classes but forgets to do it to the other.

Upvotes: 1

Related Questions