Is it possible in C# to overload a generic cast operator in the following way?


Just wondering if there is anyway to represent the following code in C# 3.5:

public struct Foo<T> {

    public Foo(T item) {
        this.Item = item;

    public T Item { get; set; }

    public static explicit operator Foo<U> ( Foo<T> a )
        where U : T {

        return new Foo<U>((U)a.Item)



I think the short answer is "Not possible. Try using a method instead"

Also seems to be dupe of this question Solution for overloaded operator constraint in .NET generics

By : Gishu

Your code boils down to the line: return new Foo

By : Gidon

This video can help you solving your question :)
By: admin