The World’s Leading Microsoft .NET Magazine
   
 
The .NET Addict's Blog

My Top Tags

                                                           

My RSS Feeds








Latest Diggs - Programming

Internet Blogs - Blog Top Sites

Site Hits

Total: 2,502,635
since: 19 Jan 2005

Objective-C Categories vs C# 3.5 Language Extensions

posted Mon 26 Feb 07

Those of you who have been using Orcas CTPs, or CTPs that don't even have the Orcas name on them (such as the LINQ Previews from way back in May '06, etc) are familiar with LINQ and maybe even LINQ to Entities and LINQ to DataSets. I've posted a few blog entries on these features. All of those features are made possible through a new low-level language feature in C# (and VB.NET, though I like to pretend that VB.NET doesn't exist) called language extension. A language extension is really just a slick way of adding code to an existing class. You can add code to any class, whether or not you are the one who wrote it. The only restriction that I'm aware of is that your language extension can only access public members of the original class (unless you're like me and you know how to cheat using Reflection...)

A C# language extension to the string class might look something like this:

static class StringExtender
{
     public static string DoSomethingFancy(this string input)
     {
        ...
     }
}

This enables you to write code like this:

string x = "Hello World";
Console.WriteLine(x.DoSomethingFancy());

Depending on which build of Orcas you have, this might generate warnings, but it will compile and you will invoke the DoSomethingFancy() method on the string.

Here is where I admit to having been a narrow-minded C# developer. When anyone works with a single technology for as long as I've worked with .NET and C#, you tend to get myopic (which is a bad thing for someone like me). Without even being aware of it, you tend to assume that everything in front of you on a daily basis is the sum total of the programming world. It becomes easy to assume that fantastically cool new features being added to your favorite language of all time are exclusive to that language. See, I assumed that C# was the only language cool enough (remember what I said about VB.NET not existing) to get language extension capabilities.

Turns out that Objective-C has had class/object extension facilities since the dawn of time. I can't find a concrete reference, but it looks like it's been around in Objective-C since well before OS X, back in the NeXT days or earlier (can any of you long-time Apple folks confirm when Categories first appeared?).

Objective-C allows you to dynamically extend and reshape existing classes through a facility known as Categories. Actually, the language extension capability of categories is a secondary effect. The true purpose of categories is to allow you to categorize similar sets of functionality that belong to multiple classes - for example, if you are creating a custom set of methods that apply to 5 or 6 different classes, you could actually store those methods in the same file, and have them apply to 5 ot 6 different classes. Purists might slap me in the face for saying this, but Categories feel sort of like compile-time aspects in a way - far more than just simple language extensions. Categories are also designed to allow for simplification of the development process when multiple developers are contributing code to the same large class. Each developer could be working on one particular aspect (pun intended) of the class' overall functionality, each stored in their own category. Whether a project like that needs to be refactored into multiple classes is outside the scope of this article :)

Anyway, here's what the header (.h) for an Objective-C category looks like:

// need to be able to locate the declaration of the original class
#import "ClassName.h"
 
@interface ClassName ( CategoryName )
- (void)doSomethingFancy;
@end

In the above sample, ClassName is the name of the class being extended, such as NSString or perhaps a class from your own project. And here's what the implementation of a category looks like:

#import "CategoryName.h" 
 
@implementation ClassName ( CategoryName )
- (void)doSomethingFancy {
// implementation
}
@end

Admittedly I had a juicier sample of an Objective-C category, but I don't have access to the MacBook Pro at the moment. Note that the implementation imports the header file for the category (the .h displayed previously), and not the header file for the original/source class. So, to add the doSomethingFancy method to the NSString class in Objective-C, your header for the category might look like this:

@interface NSString ( FancyAddOns ) 
- (void)doSomethingFancy;
@end

So I yet again stumble on something that I think is shiny and new in C# when I realize that it's been around in several places probably since I was in diapers.

tags:                

links: digg this    del.icio.us    technorati    reddit




1. Craig left...
Mon 26 Feb 07 8:13 am

yes but can objc be used to create websites since almost all the apps we get asked to build these days have this requirement? ;)


2. Ahruman left...
Mon 26 Feb 07 8:40 am

I’ve created a web applet using Cocoa. It consisted of a Foundation-based CGI (using a C library to handle the environment variables and so forth) which communicated with a server process based on AppKit (because it generated PDFs, which can’t easily be done in a command-line process). I would’t reccomend this approach, but it certainly can be done.


3. Kevin Hoffman left...
Mon 26 Feb 07 8:41 am

Not sure what creating websites has to do with extending existing classes through categories or Orcas language extensions in C#. To the best of my knowledge, if you want websites on a Mac, use Ruby or WebObjects.


4. Craig left...
Mon 26 Feb 07 9:17 am

it has nothing to do with the post - I just one of these objc topics and asked the question, I love all these different languages and tools but hey, if you can't make a site out of it - its not much use .. .to me, just me others might like client apps still :)


5. Chris Hanson left...
Mon 26 Feb 07 11:10 am :: http://chanson.livejournal.com/

The first major web application server, NeXT's WebObjects, was originally built in Objective-C atop the OpenStep frameworks (Cocoa's direct predecessor).

WebObjects was converted to 100% Java with the release of WebObjects 5.0 in 2001 since enterprise web servers were consolidating around the Java platform. But from its release in 1996 through 2000, WebObjects 1.0 through 4.5 had an Objective-C API.


6. Grady left...
Mon 26 Feb 07 1:14 pm :: http://wordparts.com/

The true purpose of categories is to allow you to categorize similar sets of functionality that belong to multiple classes - for example, if you are creating a custom set of methods that apply to 5 or 6 different classes, you could actually store those methods in the same file, and have them apply to 5 ot 6 different classes.

To my knowledge this is incorrect. (I'm just a budding Objective-C developer, but I think I'm speaking correctly here.) The original purpose of categories was to allow one to breakup a class' definition into multiple files -- sort of like recent C#'s partial classes, though category methods are added to the class at runtime rather than compile time as partial classes are. Thus categories can add or override methods even in classes whose source code you don't have -- in fact, this functionality is what categories have become most known for, with the source code organizational benefits being secondary.

Your definition sounds more like aspects to me, which you mentioned elsewhere in your post. In fact, a category applies to one and only one class (and its subclasses, of course) -- this is apparent from the category syntax in which the class name to which the category is being added must be specified.

Anyway, I've really been enjoying your articles. Thanks, and please keep them coming!


7. Kevin Hoffman left...
Mon 26 Feb 07 2:20 pm

The act of splitting up a class into multiple files is often done <i>so that you can split its functionality into related groups of methods</i>, which is the main purpose of Categories. I mentioned Aspects only to try and draw an analagy that might make Categories easier to understand for those who haven't deal with the ability to dynamically extend classes before.


8. Raed left...
Mon 26 Feb 07 2:31 pm

It is interesting because there was a whole category of Software for NeXT built on this capability. It was called objectware. The theory was you could use objects already written, only write the code necessary to customize to your app. This was considered a major advantage for the NeXTstep development environment. It actually made a great deal of sales based of this feature.


9. James Gregurich left...
Mon 26 Feb 07 2:40 pm

> if you can't make a site out of it - its not much use .. .to me

and C# isn't much use to anyone but MS-centric web developers. You do know that there are plenty of people in the world who develop neither for Microsoft platforms nor for the web, right?

Nothing stops you from developing websites in ObjC. Its a general purpose language. It would probably work just as well as C# for web development if it was integrated into web development tools as C# is. Apple made the choice to go with Java for web development because that is the standard language for high-end web development.


10. Craig left...
Mon 26 Feb 07 2:48 pm

riiiiight, thats a nice closed minded statement James.


11. James Gregurich left...
Mon 26 Feb 07 4:35 pm

>riiiiight, thats a nice closed minded statement James.

I did my time as a Windows developer...4 years...been there...done that.

Its your original comment that suggests a closed mind...not mine....you basically suggest that a tool is not worth learning if you can't write Windows web programs with it. That is completely untrue.

When I do have to work on my company's Windows products, I'll be using C++. I prefer a language that gives me full access to the underlying machine.


12. Grady left...
Mon 26 Feb 07 5:04 pm :: http://wordparts.com/

Kevin, I still don't see how Objective-C categories fit the "you could actually store those methods in the same file, and have them apply to 5 ot 6 different classes" part of your post; I also don't follow how categories allow you to "categorize similar sets of functionality that belong to multiple classes". Categories only apply to a single class and its descendants, so I'm not seeing how either of the quoted statements are accurate at all. I'm very open to being wrong, though -- I'm pretty sure I've never written a single category yet.


13. Craig left...
Mon 26 Feb 07 7:13 pm

James, show me in my post where I said anything about Windows, C# or any other Microsoft technology?? You have no idea what I'm using.


14. Kevin Hoffman left...
Mon 26 Feb 07 8:48 pm

Grady, what I meant was you could use a single file to contain the implementation of a category for multiple classes. For example, to add a method called "myFoo" to 10 different classes, you could, in theory, do that through a single myFoo.h and myFoo.m file, even though you're defining a category that goes to 10 different classes. At least that's my understanding anyway :)


15. James Gregurich left...
Mon 26 Feb 07 11:55 pm

If you aren't building web apps on Windows, then what in the world do your first two posts mean?


16. Jason Volter left...
Tue 27 Feb 07 10:26 am

So, does C# fully incorporate "The three pillars of Object Orientation"?

http://www.kirit.com/The%20three%20pillars%20of%20Object%20Orientation


17. sierra left...
Tue 27 Feb 07 3:42 pm

I think the classes are there form the beginning. I found classes on a lecturer webpage (University Darmstadt, Germany) They based on the book Object Oriented programming from Cox/Novobilski 1991 Addison-Wesley. NeXT acquired from Stepstone 1988/87 the Version 2.0 from Objective C and portet Version 4.0 as the first NexT Version.

additional: classes where in Objective C before Java was written

http://www.vorlesungen.uos.de/informatik/95-PL/00_Einfuehrung.rtfd/index.ht ml

The training there based on Prolog, Modula-2 and Objective C


18. charles Lambert left...
Mon 05 Mar 07 7:14 pm

categories were intended to serve 2 purposes. It allows you to extend a class with out inheriting from it and poluting the object space. It also allows you to use it as an informal protocol when it is a category on NSObject, meaning that its like a protocol but you only have to implement the methods you need. Sort of like an abstract base class that provides default implementations, and subclasses override the implementations they don't like. Hence the name informal protocol.


19. Miles G. left...
Fri 23 Nov 07 5:22 am

I think this feature has been available in smalltalk since the 70's. i know that a technique used by smalltalk programmers when they have a polymorphic method spread amonst classes (like an interface in java/C#) they often will also give Object the method that just raises an exception to let the programmer know they are using an object that doesn't fit the pattern (yet) if it's being incorrectly used (since all non-intended classes will inherit they exception-throwing-version of the method from Object.)

Also, this feature is used often instead of creating "Helper" classes. If you need to do something that you think might be in a standard class, but don't see it there when you check (maybe something like trying to see what week of the year it is but it doesn't exist, you would add it to DateTime instead of making a helper class.)

Point is, smalltalk was probably where objective-c got the idea in the first place, and if not, it should have been mentioned in this article if we are being historical about it. Though objective-c is much more like C# than smalltalk by far so maybe that's why it was overlooked.


Tag Related Posts

MobileMe vs. Live Mesh Throwdown - Round 1

Wed 16 Jul 08 10:33 A GMT-05

Building Model Classes in C# and Cocoa

Sun 15 Jun 08 3:13 P GMT-05
tags:            

MobileMe vs. Live Mesh - Round 1

Wed 11 Jun 08 12:20 A GMT-05

CLINQ v1.1.0.0 Released!

Fri 02 May 08 5:38 P GMT-05
tags:          

My Macbook Air is masculine, dammit!

Mon 17 Mar 08 6:59 P GMT-05
tags:          

My Macbook Air Review

Sun 02 Mar 08 4:20 P GMT-05

Video of the Macbook Air in Action

Wed 20 Feb 08 3:04 P GMT-05

LINQ to REST - A much better name for Astoria

Tue 11 Dec 07 1:23 P GMT-05
tags:        

Leopard Code Sample : Sprinkling in some Bonjour

Tue 27 Nov 07 2:32 P GMT-05
tags:        

Unexpected and Unsafe behavior in LINQ

Wed 14 Nov 07 8:09 P GMT-05
tags:    

Leopard Sample: A Bound NSCollectionView

Mon 29 Oct 07 1:41 A GMT-05

C# 3.0 - Are Object Initializers Evil, Useful, or Both?

Fri 26 Oct 07 10:53 A GMT-05
tags:    

Leopard is out - let the code samples begin!

Fri 26 Oct 07 10:09 A GMT-05
tags:          

My life is complete : iPhone SDK is CONFIRMED.

Wed 17 Oct 07 6:38 P GMT-05
tags:          

Leopard Shipping October 26th!!

Tue 16 Oct 07 4:59 P GMT-05
tags:        

Continuous LINQ - Can I write games with it?

Mon 13 Aug 07 3:09 P GMT-05
tags:        

Silverlight 1.1 Alpha Refresh

Fri 10 Aug 07 2:09 P GMT-05
tags:    

Orcas Beta 2 - might as well be a CTP

Tue 07 Aug 07 1:15 A GMT-05
tags:  

Continuous LINQ

Mon 06 Aug 07 1:21 P GMT-05
tags:    

Dynamic, Observable LINQ Views

Tue 31 Jul 07 1:21 A GMT-05
tags:        

My iPhone Review

Mon 23 Jul 07 1:09 P GMT-05
tags:        

Acropolis or Acrapolis?

Thu 05 Jul 07 12:34 P GMT-05
tags:      

Microsoft Codename Acropolis - Unwrapped

Wed 20 Jun 07 3:22 P GMT-05
tags:              

The dreaded language bleed-over has begun

Tue 19 Jun 07 6:23 P GMT-05
tags:        

My first "Acropolis" Application

Mon 04 Jun 07 1:40 P GMT-05
tags:      

Exploring the Delegate Design Pattern

Mon 14 May 07 6:30 P GMT-05

Orcas' Hidden Gem - The managed PNRP stack

Fri 11 May 07 6:45 P GMT-05
tags:        

Orcas EDM Wizard Patched

Fri 27 Apr 07 11:56 A GMT-05
tags:      

Installing Orcas Beta 1 - VMware Style

Mon 23 Apr 07 12:16 P GMT-05

Orcas Beta 1 Released

Fri 20 Apr 07 7:09 P GMT-05

Core Data - Almost too Easy?

Wed 18 Apr 07 2:23 P GMT-05

Exploring the MVC Pattern in WPF

Tue 10 Apr 07 12:51 P GMT-05
tags:                      

An experience with the Leopard beta

Mon 26 Mar 07 7:45 P GMT-05
tags: