Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}

Thanks

like image 360
LaserJesus Avatar asked Jun 22 '09 05:06

LaserJesus


People also ask

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.

What does #if mean in C?

Description. In the C Programming Language, the #if directive allows for conditional compilation. The preprocessor evaluates an expression provided with the #if directive to determine if the subsequent code should be included in the compilation process.

Can C++ be written in C?

Most compilers for C and C++ are written in C and C++. This is possible because of compiler bootstrapping.

What does if 0 mean in C?

'0' in any case is considered as false value, so when you pass 0 as an argument like: if(0) { ---statments--- } The statement part of will not get executed, and the system will directly jump to else part.


1 Answers

Conversion operators can't be generic. From the spec section 10.10, here's the format of a conversion-operator-declarator:

conversion-operator-declarator:
    implicit   operator   type   (   type   identifier   )
    explicit   operator   type   (   type   identifier   )

Compare this with, say, a method-header:

method-header: attributesopt method-modifiersopt partialopt return-type member-name type-parameter-listopt ( formal-parameter-listopt ) type-parameter-constraints-clausesopt

(Sorry about the formatting - not sure how to do it better.)

Note that the operator format doesn't include a type parameter list or type parameter constraints.

like image 162
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet