3

In class A I have a method:

  public static String GetTimestamp(this DateTime value) {
            return value.ToString("yyyyMMddHHmmssffff");
        }

I call it by:

        String timeStamp = GetTimestamp(new DateTime());

What is the difference in use if that method looked like:

  public static String GetTimestamp( DateTime value) {
                return value.ToString("yyyyMMddHHmmssffff");
            }
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • I've never seen extension methods used like that. I usually see it like `date.GetTimestamp();` or something along those lines, but they're both acceptable. – pcnThird Jan 09 '14 at 00:05

4 Answers4

4

The point of an extension method is that you could have called it like:

String timeStamp = new DateTime().GetTimestamp();

to the same effect. That’s the only change.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • That what I thought but it didn't work: `System.... DateTime()` does not contain definition.... That is what I get. – Yoda Jan 09 '14 at 00:15
  • Ok I get: Error 1 Extension method must be defined in a non-generic static class C:\Users\R\documents\visual studio 2013\Projects\HomeSecurity\HomeSecurity\VideoStream.cs 12 26 HomeSecurity – Yoda Jan 09 '14 at 00:23
  • 1
    Well, is your class `static`? You need a `static class Something { … }` for extension methods. – Ry- Jan 09 '14 at 00:26
  • In C# if I make class static does it have any drawbacks? – Yoda Jan 09 '14 at 00:33
  • Ok I see IT HAS. I can't create class extension. – Yoda Jan 09 '14 at 00:34
  • 1
    Don’t just make your containing class static or anything like that. Make a new class. – Ry- Jan 09 '14 at 00:35
  • @Yoda, If you're interested in static classes: http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp – pcnThird Jan 09 '14 at 00:35
  • Btw, you can do as @minitech suggested and create a static class *only* for extension methods. – pcnThird Jan 09 '14 at 01:05
2

Extension Methods are intended to be used as "if they were" regular instance methods of their target types:

var timeStamp = new DateTime().GetTimestamp();

other than that, there is no difference.


They were introduced in C# 3.0 to create the beautiful syntax we normally see in LINQ today, such as:

  var soldProducts = customers.Where(x => x.IsActive)
                              .SelectMany(x => x.Orders)
                              .Where(x => x.Status == OrderStatus.Completed)
                              .Select(x => x.Product)
                              .ToList;

without extension methods, this syntax would not be possible and would require many regular method calls:

var activecustomers = Enumerable.Where(customers, x => x.IsActive);
var orders = Enumerable.SelectMany(activecustomers, x => x.Orders);
var completed = Enumerable.Where(orders, x => x.Status == OrderStatus.Completed);
var products = Enumerable.Select(completed, x => x.Product);
var soldProducts = Enumerable.ToList(products);

Not to mention that type inference is also playing a big part here, since most of these methods in System.Linq.Enumerable are actually generic methods with one or several type parameters, but the C# compiler is smart enough to infer the generic type parameters and remove the need to explicitly specify them.

Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
2

With the extension method version, you can also call it with

dateTime.GetTimeStamp()

if you've includeded the namespace it's declared in.

TheEvilPenguin
  • 5,634
  • 1
  • 26
  • 47
  • Ok how to include that namespace? – Yoda Jan 09 '14 at 00:17
  • @yoda if class `A` is defined in `namespace MyNamespace` then just `using MyNamespace` in the code where you're trying to use the extension. – Federico Berasategui Jan 09 '14 at 00:17
  • I am using this extension just under the place it is defined. VS2013 tells me that `DateTime` does not contain definition of `GetTimeStamp`. – Yoda Jan 09 '14 at 00:21
  • Ok I get: Error 1 Extension method must be defined in a non-generic static class C:\Users\R\documents\visual studio 2013\Projects\HomeSecurity\HomeSecurity\VideoStream.cs 12 26 HomeSecurity – Yoda Jan 09 '14 at 00:22
2

Extension methods allow you to treat them as though they were a method inside of the type in question. So in your first example, that method can be treated as though it is a method inside of DateTime. so you could do something like this:

var foo = new DateTime();
var timestamp = foo.GetTimestamp();
Dylan Smith
  • 22,069
  • 2
  • 47
  • 62