Search code examples
c#extension-methods

Why can I add extensions methods to the string class but not to DateTime?


If I make a method like this:

public static void ExtMethod(this string);

it will show up if I invoke it like so:

string str = "";
str.ExtMethod();

but if I did this:

public static void ExtMethod(this DateTime);

this doesn't work:

DateTime date;
date.ExtMethod();

I have to call it like this:

ExtMethod(date);

So why can I make an extension method for string but not for DateTime?


Solution

  • The date variable is not assigned. You need to assign some value.
    e.g.

    DateTime date = DateTime.Now;//or some value else
    date.ExtMethod();
    

    instead of

    DateTime date;
    date.ExtMethod();