Home > Software engineering >  generic partial methods in C#?
generic partial methods in C#?

Time:10-16

Partial classes and Partial methods states:

Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.

Visually what are code examples of "Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one." and "Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one."?

I don't know what the above 2 statements look like visually in code.

CodePudding user response:

Declaration

including generic constraints:

public void Method<TName>(int name) where T : class;

Implementation

without the generic constraints repeated, and different parameter names:

public void Method<TOther>(int other)
{
    // ....
}

CodePudding user response:

Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.

public partial class C {
    public partial void M<T>(int x);
}

public partial class C {
    public partial void M<U>(int y) {
        // implementation goes here...
    }
}

The two declarations of M have different type parameter names (T and U), and different parameter names (x and y).

Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one.

This is incorrect. The C# language specification says:

Corresponding type parameters in the declarations must have the same constraints (modulo differences in type parameter names).

  • Related