Casting objects between different libraries

I have a dll where I defined a specific object (say Point3) and other methods.

I have another dll where I use the same object, but since I want to maintain independence, I declared a new Point3_ object. It is just a container of elements (x, y, z).

Finally, I have a project in which I use both libraries, I would like to know if there is a clean way to cast from Point3 to Point3_, assuming they have compatible types.

Right now I am writing something like:

p_ = new Point3_(pX, pY, pZ); 

I would like something like:

 p_ = (Point3_)p; 

PS: I apologize if this is a duplicate, but I was not sure how to look for it on the Internet.

Thank you in advance

EDIT: I am not opposed to implementing the cast code, but I want to write it in a third project that knows both libraries. Thus, I can separately develop libraries.

+5
source share
4 answers

You can achieve this by implementing the explicit operator

 public class Point3_ { // Converts a Point3 to Point3_ by explicit casting public static explicit operator Point3_(Point3 p) { return new Point3_(pX, pY, pZ); } } 

If you change explicit to implicit , then p_ = p; will also work.

+2
source

Not really. The only option is to implement your own casting operators, but that will mean exactly the connection you are trying to avoid.

However, you could write extension methods to handle this for you - they can be declared in some interop library or in your own consumer project.

 public static Point3_ AsPoint3_(this Point3 @this) { return new Point3_(@this.X, @this.Y, @this.Z); } 

just called

 p_ = p.AsPoint3_(); 
+5
source

You can also use something like Automapper to automatically display. This is a mapping based on the same property names.

 Mapper.CreateMap<Point3, _Point3>(); _Point3 point = Mapper.Map<_Point3>(new Point3()) 
+1
source

If you must declare an interface in your first library:

 public interface IPoint3 { public int X; ... etc ... } 

And then both classes implement this interface (assuming that one library refers to another or can even declare this interface in a separate library), then you can refer to them in your calling code via the interface, for example:

 List<IPoint3> results = new List<IPoint3>(); results.Add(new Point3()); results.Add(new _Point3(); int output = results.Sum(p => pX); 
0
source

All Articles