C# Expression body inference?

Viewed 125

Let's say I have a small example class:

public class Test
{
    public Test() {}
    public List<int> Numbers { get; set; } = new List<int>();

    public void AddNumber(int number) => Numbers.Add(number);
    public void RemoveNumber(int number) => Numbers.Remove(number);
}

How come the above excerpt does not give any warnings or errors when the void return type method named RemoveNumber uses the bool return type List<int>.Remove(int item) method? Should the return types of both the calling method and the called method not match?

1 Answers

The C# documentation's page on Expression-bodied members says (emphasis mine):

An expression-bodied method consists of a single expression that returns a value whose type matches the method's return type, or, for methods that return void, that performs some operation.

So the C# language is making a special-case exception for void, so so given a member of this form:

T Name() => Expr;

...then typeof(Expr) must match T - excepting when T is void (as it is in your case) in which case Expr is a method that performs some operation and Expr's return value is implicitly discarded.

C# does not support type inference for scenarios like these (if it did you wouldn't have specified void anyway).


As for why there's no warning or error - that's because you have Code Analysis turned-off. If you were to enable it in your project then your code would get a CA1806 warning because the return bool from Numbers.Remove(number) is being ignored - the fix is to add an explicit discard (_ = ), like so:

public void RemoveNumber(int number) => _ = Numbers.Remove(number);
Related