Type constraints in code block #7794
-
public static void Calc<T>(T num) where T: INumber<T>
{
// do something
}
public static void Do<T>(T value)
where T: ISomeInterface
{
Calc(value); // compile error (type constraint)
if (value is INumber<T>) {} // compile error (type constraint)
if (value is INumber<int> num) Calc(num); // ok, but boxing
if (value is int num) Calc(num); // ok, no boxing in RELEASE, boxing in DEBUG
// proposal
if (T is T1 where T1: INumber<T1>) {
// in this block
// T1: INumber<T1>
// T: ISomeInterface, INumber<T>
Calc(value); // -> Calc<T>(value) where T: ISomeInterface, INumber<T>
T1 num = value; // no boxing
value++; // ok
}
if (T is int) // the same as typeof(T) == typeof(int)
{
Calc(value); // ok -> Calc<int>(value)
}
// also
if (T is unmanaged) { }
if (T is class) {}
if (T is struct) {}
// complex
if (T is IDictionary<T1,T2>
where T1: unmanaged, INumber<T1>
where T2: struct, INumber<T2>
) {
var arr = value.ToArray(); // arr: KeyValuePair<T1,T2>[]
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
KennethHoff
Dec 28, 2023
Replies: 1 comment 1 reply
-
Duplicates #6308 |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
333fred
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Duplicates #6308