Why must I provide explicitly generic parameter types While the compiler should infer the type?

Inference doesn’t consider the return type; you can, however, try splitting the generics; for example, you could write code to allow:

.Cast().To<Type2>()

by having (untested; indicative only)

public static CastHelper<T> Cast<T>(this T obj) {
    return new CastHelper<T>(obj);
}
public struct CastHelper<TFrom> {
    private readonly TFrom obj;
    public CastHelper(TFrom obj) { this.obj = obj;}
    public TTo To<TTo>() {
       // your code here
    }
}

Leave a Comment