I have a big object:
class BigObject{
public int Id {get;set;}
public string FieldA {get;set;}
// ...
public string FieldZ {get;set;}
}
and a specialized, DTO-like object:
class SmallObject{
public int Id {get;set;}
public EnumType Type {get;set;}
public string FieldC {get;set;}
public string FieldN {get;set;}
}
I personally find a concept of explicitly casting BigObject into SmallObject - knowing that it is a one-way, data-losing operation - very intuitive and readable:
var small = (SmallObject) bigOne;
passSmallObjectToSomeone(small);
It is implemented using explicit operator:
public static explicit operator SmallObject(BigObject big){
return new SmallObject{
Id = big.Id,
FieldC = big.FieldC,
FieldN = big.FieldN,
EnumType = MyEnum.BigObjectSpecific
};
}
Now, I could create a SmallObjectFactory
class with FromBigObject(BigObject big)
method, that would do the same thing, add it to dependency injection and call it when needed... but to me it seems even more overcomplicated and unnecessary.
PS I'm not sure if this is relevant, but there will be OtherBigObject
that will also be able to be converted into SmallObject
, setting different EnumType
.
.ToSmallObject()
method (orGetSmallObject()
). A momentary lapse of reason - I knew something is wrong with my thinking, so I've asked you guys :)ToSmallObject
method.