#implicit operator between two Wrapper<T> instances, where T is an different type for each

1 messages · Page 1 of 1 (latest)

orchid isle
#

I have a Wrapper<T> struct type. I'd like to write an implicit operator, which can convert between two Wrapper<T> instances, in which the generic type T is different, for each instance:

public struct A
{
    public int value;
}

public struct B : IConvertable<A>
{
    public float value;

    public void From(A source)
    {
        value = (float)source.value;
    }

    public A To()
    {
        return new A
        {
            value = (int)value
        };
    }
}

public class Wrapper<T>
{
    public T target;

    // Does not compile:
    public implicit operator Wrapper<Q> <Q>(Wrapper<T> source) where Q : IConvertable<T>
    {
        Wrapper<Q> dest = new();

        dest.From(source);

        return dest;
    }
}

public interface IConvertable<T>
{
    void From(T source);
    T To();
}

As you can see, the implicit operator above won't compile. I'm guessing C# just doesn't allow for implicit operators with extra generic type parameters.

Is there any way to achieve what I'm trying to do? Thanks for any help or advice.

fair crescent
orchid isle
#

Ty.

How would that work? If I made methods to convert A <-> B, where would the generics come in?

fair crescent
#

Well in this case im not too sure how you plan to use A, B and Wrapper but i was just imagining something like

public Wrapper<Q> ConvertTo<Q>() where Q : IConvertable<T>, new()
{
}

I dont think the other code makes sense because A isn't convertible so in this case i dont think you could convert from B to A

#

and Wrapper also isn't convertable so dest.From(source); would have to be on the dest.target after you set it instead

fair crescent
#

imo it'd make more sense though if some of the logic moved to A. Like if you want a conversion from A <-> B, then A can define one of these methods rather than B defining both "from" and "to"

#

its up to you if you want to move "from" or "to", doesn't really matter. I do think the way I wrote it currently is unclear with "ConvertFrom" because <B> is beside it so ConvertTo makes more sense

orchid isle
#

Sadly, I don’t have access to A. It’s predefined in another library.

fair crescent
#

I see, well tbh im not sure how you'd make an all encapsulating method for the "To" part here