Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting objects between different libraries

Tags:

c#

casting

I have a dll where I defined a specific object (let's say, Point3), along with different methods.

I have another dll where I use the same kind of object, but as I want to keep independency I declared a new object Point3_. This is just a container of the elements (x,y,z).

Finally I have a project where I am using both libraries, I would like to know if there is a clean way to cast from Point3 to Point3_, assuming that they have compatible types.

Right now, I am writting something like:

p_ = new Point3_(p.X, p.Y, p.Z);

I would like something like:

p_ = (Point3_)p;

PS: I am sorry if this is a duplicate, but I was not sure of how to search for this in the web.

Thanks in advance

EDIT: I don't mind implementing the casting code, but I want to write it in the 3rd project, which is aware of both of the libraries. This way I will be able to separately develope the libraries.

like image 856
leandro Avatar asked Mar 16 '23 00:03

leandro


2 Answers

Not really. The only option is implementing your own casting operators, but that would mean exactly the kind of coupling you're trying to avoid.

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

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

called simply as

p_ = p.AsPoint3_();
like image 136
Luaan Avatar answered Mar 29 '23 11:03

Luaan


You can achieve this by implementing an explicit operator

public class Point3_
{
    // Converts a Point3 to Point3_ by explicit casting
    public static explicit operator Point3_(Point3 p)
    {
        return new Point3_(p.X, p.Y, p.Z);
    }
}

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

like image 23
György Kőszeg Avatar answered Mar 29 '23 10:03

György Kőszeg