[ Likely a duplicate but I've not found it ]
I was surprised to receive the error 'List<int>' does not contain a definition for 'Sum'
during the below usage?
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Test
{
public class Foo: List<int>
{
public int Total => base.Sum();
}
}
It seems that extension methods are not available after inheritance? Or I'm missing something?
P.S. I'm aware of Why not inherit from List?
The key to understanding this behavior is that, contrary to this
, base
itself is not an expression. C# specification for the base keyword (11.7.13 Base access):
Note: Unlike this, base is not an expression in itself. It is a keyword only used in the context of a base_access or a constructor_initializer (§14.11.2). end note
If you look at the C# specification for extension methods (11.7.8.3 Extension method invocations) you'll notice that extension methods apply only to expressions:
In a method invocation (§11.6.6.2) of one of the forms
«expr» . «identifier» ( )
«expr» . «identifier» ( «args» )
«expr» . «identifier» < «typeargs» > ( )
«expr» . «identifier» < «typeargs» > ( «args» )if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation. If «expr» or any of the «args» has compile-time type dynamic, extension methods will not apply.
For the same reason of base
itself not being an expression, you can't do these things with base either:
var stuff = base;
CallSomeMethod(base);