1

C# has extension methods.

Some static methods of the string class can be rewritten as extension methods e.g. String.IsNullOrEmpty.

Is there a reason why there are no default extension method for the string class that provide the same functionality as the static class?

Acerbic
  • 100
  • 1
  • 9

3 Answers3

4

Yes. A really good one.

It PREDATES the existence of extension methods. It simply was there first.

There are quite some similar scenarios around. Lots of API taking a typeof but not having a generic version, i.e. - all predating generics.

TomTom
  • 61,059
  • 10
  • 88
  • 148
0

Look at the string.IsNullOrEmpty documentation (specifically, the "Applies to" section).

This method existed since .NET Framework 2.0.

If you look at the history of C# from the official docs, you can simply find that extension methods came with C# 3.0, which was around .NET Framework 3.5.

Note: Don't mix between C# versions and the .NET versions.

Youssef13
  • 3,836
  • 3
  • 24
  • 41
-4

Another reason is the method would fail if the string reference was null. Consider something like this:

string x = null;
if (x.isNullOrEmpty()) ...

This call would obviously cause an error.

Mark Wagoner
  • 1,729
  • 1
  • 13
  • 20
  • 2
    Nope. Actually calling an extension method with a null this is legal. https://stackoverflow.com/questions/847209/in-c-what-happens-when-you-call-an-extension-method-on-a-null-object – TomTom Jun 25 '20 at 11:00