Question

I have a generic struct and two synonyms with defined generic type parameter. I want to define type conversions between these two types like this:

using X = A<int>;
using Y = A<long>;

struct A<T>
{
    private T data;

    public A(T data)
    {
        this.data = data;
    }

    public static explicit operator X(Y value)
    {
        return new X((int)value.data);
    }
    public static implicit operator Y(X value)
    {
        return new Y(value.data);
    }
}

and here is an example how I want to use the struct:

class Program
{
    static void Main(string[] args)
    {
        X x = new X(1);
        Y y = new Y(2);

        x = (X)y; // explicit cast with precision loss
        y = x; // implicit cast without precision loss
    }
}

Unfortunately each "using" creates new specific definition of the struct and C# compiler treats synonym structures not as a subset of a generic structure, but as an individual structure. That's why compiler reports errors:

  1. "ambigious between X.static implicit operator Y(X) and Y.static implicit operator Y(X)".
  2. "User-defined conversion must convert to or from the enclosing type".

Does anybody knows a way to realize this type conversions without changing type to class?

UPDATE: I'm using .NET 4.

Was it helpful?

Solution

The error

User-defined conversion must convert to or from the enclosing type.

means that your conversion operators need to convert to/from A<T>. Yours are converting to/from A<int/string>. That's not the same thing (much less general at least).

So this cannot work. You have to find some other way to do the conversions. Maybe runtime casting can help here (define the operators as acting on A<T> and do casting inside of them).

I think this problem is unrelated to the type synonyms. In fact they made the question harder to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top