Resolution of extension method with parameters of type nullable value

public static class Extension
{
    public static void Test(this DateTime? dt)
    {
    }
}


void Main()
{
    var now = DateTime.Now;
    Extension.Test(now); // ok
    now.Test(); // compile time error
}

I am just wondering why the compiler cannot solve the same method when called as an extension?

+3
source share
5 answers

A is DateTime not converted to Nullable<DateTime> explicitly.

Specification C #, 7.6.5.2. Call extension method:

The extension method is eligible if:

  • Mj is accessible and applicable when applied to arguments as a static method, as shown above.
  • An implicit conversion of an identity, reference, or box exists from expr to the type of the first parameter Mj.

...

If the candidate set is not found in any namespace declaration or in the compiler, a compile-time error occurs.

, DateTime Nullable<DateTime> null :

DateTime now = DateTime.Now;
((DateTime?)now).Test();

DateTime? now = DateTime.Now;
now.Test();
+3

+1

Fix:

  public static class Extension
  {
    public static void Test(this DateTime? dt)
    {
    }
  }

  public class Program
  {
    private void Main()
    {
      DateTime? now = DateTime.Now;
      Extension.Test(now); 
      now.Test();  
   }
  }
+1

var . . DateTime.Now var, DateTime, Nullable<DateTime>, .

var ( #)

, NULL:

public static T? GenericMethod<T>(this T? source) where T : struct
{
    //Do something
}

, , :

DateTime? dateTimeNullable = DateTime.Now;
dateTimeNullable.GenericMethod();

int? intNullable = 0;
intNullable.GenericMethod();
+1

Since you wrote the extension for DateTime?, not for DateTime.

        DateTime? now = DateTime.Now;
        Extension.Test(now); // ok
        now.Test(); // no compile time error

or

        var now = new DateTime?(DateTime.Now);
        Extension.Test(now); // ok
        now.Test(); // no compile time error

will work.

0
source

you need to create your variable now with a null type corret:

 DateTime? dateTime = DateTime.Now;
 dateTime.Test();
0
source

All Articles