Reputation: 2098
I'm trying to cast a generic type to a fixed one.
The following is what I expect to work, but there is a fundamental flaw in it.
public class Wrapper<T>
{
public T Value;
static public implicit operator TypeWithInt(Wrapper<int> wrapper)
{
return new TypeWithInt(wrapper.Value);
}
static public implicit operator TypeWithFloat(Wrapper<float> wrapper)
{
return new TypeWithFloat(wrapper.Value);
}
static public implicit operator TypeWithDouble(Wrapper<double> wrapper)
{
return new TypeWithDouble(wrapper.Value);
}
}
The above code doesn't compile with the following error:
User-defined conversion must convert to or from the enclosing type
As Wrapper<int>
is different from Wrapper<T>
it'll never work, because Wrapper<int>
isn't the enclosing type.
So my question is: How can I make this casting work? Is there a way?
Upvotes: 0
Views: 819
Reputation: 18965
Your object model is a bit nonsensical because the .NET type system only considers at most 2 types at a time:
/* type 1 (int) */ int a = "abc" /* type 2 (string) */;
Yet you're trying to force another type in the middle which doesn't mesh. This isn't a limitation of the type conversion process, but instead, a limitation of the language. Every assignment (the phase at which implicit type conversions are enforced) can have at most 2 active parties, the left (int
in the example above) and the right (string
in the example above). Cascading implicit casts are not supported and would likely be really hard to code for.
The only possible solution I see to your problem would be to make this transition more visible to your user and add ToInt
, ToFloat
methods on Wrapper<T>
to allow it to do its job.
Another point of interest might be the performance impact for doing this... the net result of your proposed wrapper is a boxing operation which may lead to unfortunate performance if you're working with a fair load. The alternative would be to rearchitect your application to be less type specific. Doing so would likely also eliminate the issue you're currently facing.
Upvotes: 3
Reputation: 887305
You could add the cast to an abstract non-generic base class and make the generic class inherit it.
Upvotes: 0