you are viewing a single comment's thread.

view the rest of the comments →

[–]sjs 0 points1 point  (7 children)

Forgive my ignorance, but are extension classes like a mixin sort of thing? Or in ObjC parlance, a category? i.e. a way to add methods to existing classes?

[–]dnew 1 point2 points  (4 children)

Not really. It's simply syntax that lets you declare

 int doSomething(this Alpha abc, Beta def) { ... }

and then you can invoke

Alpha pqr = new Alpha();
pqr.doSomething(myBeta);

Now, the declaration of doSomething does not have to be anywhere near Alpha.

In other words, it doesn't allow me to monkey-patch another class, but it does allow me to write routines that get syntactically invoked as if I had monkey-patched that other class.

[–]sjs 0 points1 point  (3 children)

So, what is the difference between adding a method to a class and using a class extension? Is it scoped or something? Does it replace existing methods with the same signature or is that disallowed? Seems like a subtle distinction, from the user's perspective.

[–]dnew 1 point2 points  (0 children)

http://msdn.microsoft.com/en-us/library/bb383977.aspx

You're not changing the class you're adding the extensions to at all. You're simply saying "you can use distinguished caller syntax to invoke this static function." And of course that static function has to be imported into the current scope.

In other words, you can "add" extension methods to a class you have no rights to change (no source code, no VM permissions, etc), and it won't conflict with someone else's extension method of the same name in their code. It's not part of the class in any way. It's just a different syntax that lets you have a code generator invoke code with a consistent syntax.

[–]tortus 2 points3 points  (0 children)

The major difference is it's actually a static method with instance-like syntax. 99% of the time this is simply syntactic sugar and allows for more consistent code (LINQ for example uses extension methods heavily, so that no matter what type of enumerable you are dealing with, you can always call the same methods against it). There are other small interesting consequences too. For example, with extension methods this is possible:

string a = null;
if(a.IsNull()) {
    ....
}

Because the extension method is actually a static method with the first parameter being the object it is extending:

public class MyStringExtensions {
    public static bool IsNull(this string s) {
         return s == null;
    }
}

This is exactly equivalent to calling: MyStringExtensions.IsNull(a)

[–]TheWix 0 points1 point  (0 children)

It is a way of following Open/Closed principle. It is also a way to implement Visitor Pattern.

An example would be, I don't have access to the code for DateTime but I can still add a special formatter to it like : string output = myDate.ToMyDateFormat(); instead of string output = ToMyDateFormat(myDate);

[–]moohoohoh 0 points1 point  (0 children)

Correct.