Building a Class
Throughout the rest of this chapter we're going to be building a class that has progressively more functionality. The goal is to walk you through the process of designing and building a full-featured class for both the iPhone and Windows Phone 7 so that you can compare and contrast and map your existing iPhone skills (if any) to how classes are created in C#.
To demonstrate class creation, we need some behavior and data that we want to model. Throughout the rest of the chapter we'll be working on a class that might show up in a game. Because we are good little programmers that have been following the advice of those who know better, this class will model just behavior, logic, and data encapsulation and will not have anything to do with UI. In short, this class is a pure model and not a view.
The class we're going to build as a starting point is a class that models the logic, data encapsulation, and behavior of an object that can participate in combat in a hypothetical mobile game. We'll call this class a Combatant.
To start with, we'll create an empty class. In Listings 3.1 and 3.2, respectively, you can see the code for the Objective-C header (.h) and implementation (.m) files. Listing 3.3 shows this same (utterly empty, and completely useless up to this point) class in C#.
Listing 3.1. Combatant.h
@interface Combatant : NSObject { } @end
In the preceding code, you can see the stock contents of an Objective-C header file as they would look immediately after creating an empty class using an Xcode template. There really isn't much to see here. The important thing to keep in mind when learning C# is that C# classes do not separate the code into header and implementation files.
Listing 3.2. Combatant.m
#import "Combatant.h" @implementation Combatant @end
The preceding code is the implementation file for an Objective-C class. This is where all the actual implementation code goes, whereas the header file is used to allow other code that references this class to know how the class behaves and what data it exposes.
Listing 3.3. Combatant.cs
using System; namespace Chapter3 { public class Combatant { } }
Finally, Listing 3.3 shows the same empty class implemented in C#. If you created your own empty class by adding one to a WP7 project, you probably noticed a whole bunch of extra using statements. For clarity, I removed those from Listing 3.3. There's not much to see here, and we haven't gotten to any of the fun stuff. The purpose of this section was to help you get your head around the difference between how classes are stored on disk in iOS and C#, and we will progressively go through more OOP comparisons throughout this chapter.