- 
                Notifications
    You must be signed in to change notification settings 
- Fork 1.4k
Description
Describe the problem this feature would solve
The new ThrowHelper APIs added in #3346 currently can't be used within switch statements or in cases where users need a return value from the invoked API in order to make the C# compiler happy. Consider this sample:
public static int Test_1(int x)
{
    return x switch
    {
        42 => 0,
        _ => throw new ArgumentException("Fail", nameof(x))
    };
}That throw can't be replaced with a ThrowHelper call, as they all return void. This forces users to either manually write a throw function, which is verbose and defeats the whole point of having the ThrowHelper APIs, or to leave the exception there and get terrible codegen, which again defeats the whole point of worrying about this in the first place.
Describe the solution
We should also offer overloads of all the ThrowHelper APIs with a dummy T return, so that devs can use them in cases like this.
The above example would become as follows:
public static int Test_2(int x)
{
    return x switch
    {
        42 => 0,
        _ => ThrowHelper.ThrowArgumentException<int>("Fail", nameof(x))
    };
}Which produces a very nice codegen:
C.Test_2(Int32)
    L0000: sub rsp, 0x28
    L0004: cmp ecx, 0x2a
    L0007: jne short L000d
    L0009: xor eax, eax
    L000b: jmp short L002c
    L000d: mov rcx, 0x23a7a40c000
    L0017: mov rcx, [rcx]
    L001a: mov rdx, 0x23a798da3a0
    L0024: mov rdx, [rdx]
    L0027: call ThrowHelper.ThrowArgumentException[[System.Int32, System.Private.CoreLib]](System.String, System.String)
    L002c: nop
    L002d: add rsp, 0x28
    L0031: retDescribe alternatives you've considered
Additional context & Screenshots
Full sharplab.io sample here.