1

I have an extension method:

public static int DoStuff(this MyEnum? enumValue) 
{
  ...
}

I want to invoke it on a value of MyEnum which is known to be not null:

MyEnum enumVal = ...
var x = enumVal.DoStuff(); // compiler error!

Error:

error CS1928: 'MyEnum' does not contain a definition for 'DoStuff' and the best extension method overload 'MyExtensions.DoStuff(MyEnum?)' has some invalid arguments

I can work around it by declaring an overload of the extension:

 public static int DoStuff(this MyEnum enumValue)
 {
     return DoStuff((MyEnum?)enumValue); 
 }

Alternatively, I can invoke the extension class explicitly:

var x = MyExtensions.DoStuff(enumVal);

But this is non-intuitive. Why can't an extension of a Nullable<T> accept a value of type T, just like any normal method signature can?

Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
  • 3
    cause `MyEnum` is not nullable – Rahul Sep 13 '17 at 12:22
  • 1
    they aren't the same type. – Daniel A. White Sep 13 '17 at 12:22
  • Besides a `Nullable` is definitely not a `T`. – Panagiotis Kanavos Sep 13 '17 at 12:23
  • @Rahul if I have a normal method `void DoStuff(MyEnum? enumVal) {}`, I can call it passing a value of type `MyEnum`. – Shaul Behr Sep 13 '17 at 12:23
  • @PanagiotisKanavos please note my edit: the question is why extension methods won't work on type `T`, when `T` is a valid argument for a parameter of type `Nullable`? – Shaul Behr Sep 13 '17 at 12:29
  • 1
    @ShaulBehr that's *not* the same. You can also use `MyStaticClass.DoStuff(enumValue)` the same way. This works because the value is *converted* to `Nullable`. Extension methods work on the concrete type though. The compiler is looking for extension methods that match the type exactly, not through implicit conversions – Panagiotis Kanavos Sep 13 '17 at 12:30
  • I think the language spec says so, but the wording is fairly thick. It demands an *implicit identity* conversion in order to consider an extension method. But this requires an implicit nullable conversion, a different animal. Well, regardless, it ain't going to happen without a (MyEnum?) cast. – Hans Passant Sep 13 '17 at 12:40

1 Answers1

5

Basically, extension methods (in contrast to method arguments) don't consider implicit conversions. And MyEnum? value = nonNullableMyEnumValue is using the implicit conversion, it is not the same type. You would run into the same situation with any other implicitly convertible type.

Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
grek40
  • 13,113
  • 1
  • 24
  • 50