tags:

views:

140

answers:

4

I have an ObjectA whose property values will always be assigned to another object's (ObjectB) properites. What I have been doing is to have a service class instantiate the receiveing ObjectB and then assign the values to the new object from ObjectA. Should I instead be sending the entire objectA directly to Object B in a setter parameter or other method? What are best practices here if any?

EDIT: In a Service class:

public AssignValues (objectA)
{
ObjectB objectB= new ObjectB();
objectB.prop1= ObjectA.prop1;
objectB.prop2= ObjectA.prop2;
}

OR

public AssignValues(objectA)
{
ObjectB objectB= new ObjectB();
objectB.SetValuesFromObjectA= objectA;
}

OR

public AssignValues(objectA)
{
ObjectB objectB= new ObjectB();
objectB.SetValuesFromObjectA(objectA);
}

OR

public AssignValue(objectA)
{
ObjectB objectB= new ObjectB(objectA);
}
+2  A: 

It's hard to answer because we don't know what these classes are. You could say, "oh, I will always pass objectA to objectB's constructor" and wind up with ...

public Chicken( Gorilla g )
{
  this.IsAlive = g.IsAlive;
}

... or something just as nonsensical. There are so many ways to do what you want to do, the fundamental question of the "right way" depends completely what you're doing.

JP Alioto
+2  A: 

Sounds like there's an Object b constructor that takes a single parameter, an Object A:

 // ctor:
 ObjectB( const ObjectA& a ) {
   prop1= a.prop1;
   prop2= a.prop2;
 }

 // or ctor:
 ObjectB( const ObjectA& a ) : prop1(a.prop1), prop2(a.prop2) {
 }

 . . . 
 // use
 ObjectB b(a);
tpdi
A: 

If the objects are of the same type, I would probably prefer to use a Clone() (shallow-copy) method.

If the objects are of different types, I would probably write a method that looks like your first case to keep the two types separated. Optionally, I might do that as an extension method that takes objectA and objectB (if either one is a struct, you might have to do that by ref or return value). As I said, The main reason I would not want to use a constructor or class/instance method in this case is that you are now tying the two types together when they may not necessarily have to really know about each other.

Erich Mirabal
A: 

Have you considered dependency injection with AutoFac? It allows you to declare what the relationships are before actually making anything. Then make, use, and clean-up nicely.

GregC