C# implicit operator for class with generic type to other generic type

91 views Asked by At

I got a C# class with a generic type. I'd like to have an implicit operator which converts an instance of this class to an instance of the same class with another generic type parameter.

class MyClass<T>
{
    public static implicit operator MyClass<TOther>(MyClass<T> self)
    {
        /* conversion */
    }
}

However the C# compiler says "The type or namespace name 'TOther' could not be found".

Is there a way to achieve my goal?

1

There are 1 answers

1
Piroozeh On

The problem with your code is that you are trying to use a generic type parameter (TOther) that is not defined in the scope of your class (MyClass). The compiler cannot infer what type TOther is supposed to be, and therefore gives you an error.

To achieve your goal, you need to define the generic type parameter TOther either at the class level or at the method level. For example, you can do:

// Define TOther at the class level
class MyClass<T, TOther>
{
    public static implicit operator MyClass<TOther, T>(MyClass<T, TOther> self)
    {
        // conversion
    }
}