C# programming introduced to Objective-C programmers (Windows Phone 7) Part 2

Inheritance

Like Objective-C, C# also uses a single inheritance mechanism. Inheritance is specified by listing the parent class after the name of the class as shown below. In the above example, the class Rectangle inherits from the class Shape, whereas the class Square inherits from the class Rectangle.

tmpC-49_thumb_thumb

In C#, the constructor of the base class is automatically invoked when constructing an instance of a derived class. However, a derived class can invoke a specific constructor of the base class if needed as shown in the constructor of the Square class.

tmpC-50_thumb_thumb

In contrast to Objective-C, a C# derived class may not override a method by just redefining it. The class must use the keyword "override" in its method definition.


tmpC-51_thumb_thumb

Objective-C provides protected variables, but methods cannot be protected. In C#, access to fields, properties and methods can also be controlled using the protected modifier. You can implement protected variables in C# by using the protected access modifier, as shown below:

tmpC-52_thumb_thumb

While Objective-C and C# use different syntactic notation for static methods or variables, they behave the same way. C# uses a ‘static’ modifier to denote class level methods, fields or properties. Everything else is at an instance level. In the above example, counter is a class level variable, protected static int counrter=0;

Abstract Classes

Abstract classes, are classes that cannot be instantiated. While Objective-C does not provide a syntax for abstract classes, many programmers use them by returning NULL from the abstract class init method. The class Shape, defined above in C#, is an abstract class and requires that both Area and the method contains must be overridden in any derived classes.

tmpC-53_thumb_thumb

Interfaces

Objective-C protocols and C# interfaces are similar. In the example below, IThreeDShape defines an interface that is implemented by the Cube class.

tmpC-54_thumb_thumb

Polymorphism

Polymorphism works the same way in both Objective-C and C#. A C# derived class can be passed as a parameter to a method that expects a base class. Similarly, a class that implements a particular interface can also be passed as a parameter to the method. This is shown in the example below, where an object of the class Cube is passed as a parameter, where the method expects an object of the class IThreeDShape.

tmpC-55_thumb_thumb

Structs

In contrast to the C-based structs used in Objective-C, C# structs are closer to classes. C# structs can have constructors, methods and properties as well as access modifiers. However, the primary difference between a struct and a class is that a struct is a value type, versus a class, which is a reference type.

tmpC-56_thumb_thumb 

Object Lifecycle – Creation and Deletion of Objects

Memory management is very different in Objective-C and C#. In contrast to Objective-C, C# performs automatic memory management. As we saw earlier, developers do not allocate memory, but use the "new" operator to create objects on the heap and initialize them. Equally important, in C#, the developer is not responsible for tracking memory usage or knowing when to free memory. When the object is no longer accessed by the code, the object is eligible for garbage collection. Periodically, the .NET CLR garbage collector frees up the memory for such objects.

In rare circumstances, developers may need to perform cleanup at the time the object is destroyed. C# allows the use of destructors, but in practice this is rare.

Other Topics

Type Checking v/s Reflection

In Objective-C, you can check the type of the class or determine if an object supports a particular method and invoke the method on that object. In C#, reflection is a versatile feature. You can use reflection to get the type information from an existing object, dynamically create an instance of a type, bind the type to an existing object, invoke its methods or access its fields and properties.

The following table explains the mapping between dynamic type checking in Objective-C and the corresponding C# reflection features.

Objective-C Dynamic Type Checking

Explanation

C# Reflection

isKindOfClass: classObj

Is Object a subclass or

type.IsSubclassOf(typeof(BaseClass))

member

isMemberOfClass: classObj

Is Object a member of

object.getType() or typeof

respondsToSelector: selector

Does the object implement the method

type.GetMethod(MethodName)

instancesRespondToSelector: selector

Does the class respond to the method

type.GetMethod(MethodName)

performSelector: selector

Invoke a method

type.InvokeMember(…)

Exception Handling

Exception handling is similar in C# and Objective-C. You use a try-catch block to handle exceptions. Additionally, you can either catch specific exceptions or use a catch-all statement. This is similar to @try, @catch and @finally statements in Objective-C.

tmpC-57_thumb[2]

Key class libraries compared

Strings

C# provides a very comprehensive string class, which gives you all the features that you are familiar with in the NSString class.

Objective-C Feature

C#

Notes

NSString

String greeting = "Hello WP7!"; Int length = greeting.Length;

Comparison

String color = "pink"; If (color == "red")

System.Console.WriteLine("Matching

Strings can be compared using ==. They can be compared lexicographically using compare.

colors!");

string name = "Joe"; if (string.compare(name, "Jack") > 0) System.Console.WriteLine(name + " comes later");

Concatenation

System.Console.WriteLine (greeting + " You rock!")

Strings can be concatenated with simple ‘+’ operator. (This is called operator overloading)

Splitting

string rainbow = "Violet, Indigo, Blue, Green, Yellow, Orange, Red"; string[] rainbowColors = rainbos.Split(‘,’); foreach (string color in rainbowColors) System.Console.WriteLine (color);

Arrays

Objective-C Feature

C#

Notes

Arrays of primitive types such as int, float

int[] table; table = new int[3];

string[] names = new string[3] {"Peter", "Paul", "Mary"};

Array size is not part of the array declaration.

Arrays are explicitly initialized.

Multi-dim arrays of primitive types

Int[,] mAray; Int[][] jaggedArray;

string[][] singers = {new string[] {"Peter", "Paul", "Mary"}, new string[]{"Paul","Art"}};

C# supports jagged arrays, or arrays of arrays, and they need not be rectangular. Note Arrays of strings, i.e. objects, work the same way.

NSArray – Immutable Arrays of objects

There is no counterpart to immutable arrays in C#.

NSMutableArray Mutable array of objects

List<string> colors = new List<string>; //list of strings

Colors.Add("Red");

You can use Lists as a replacement for mutable arrays.

Colors.Add("Green"); Colors.Insert(1,"White"); String myColor = Colors[0]; //"Red" Colors[colors.IndexOf("Red")] = "Pink"; // replace Red with pink

You may also use ArrayLists.

Dictionaries

C# provides a generic dictionary class that provides the functionality of NSMutableDictionary. It allows addition, lookup and removal of objects in the dictionary. Since it uses generics, it also utilizes strong typing.

Objective-C Feature

C#

Notes

NSDictionary – Immutable dictionary

There is no counterpart to immutable dictionary in C#.

NSMutableDictionary -Mutable dictiojary of objects

tmpC-58

You can use Dictionary as a replacement for NSMutableDictionary.

tmpC-59
tmpC-60
tmpC-61
tmpC-62
tmpC-63
tmpC-64

New features of C#

Generics

Generics introduce the notion of type parameters, that make it possible to design classes that are type safe, even though the actual type is deferred till the object instantiation. For example, here is how you define a generic stack:

tmpC-65_thumb[1][2]

The Stack<T> uses T as a type parameter allowing you to instantiate a stack of any type, e.g. Stack<int> or Stack<string> and use them in a type safe manner.

Use of generics is closest to the use of id in Objective-C collection classes such as NSDictionary.

Operator Overloading

Operator overloading permits a user defined implementation of user-defined operators for user-defined classes. Consider the following example of a Complex number struct. Operator overloading allows you to define a ‘+’ operation using a natural syntax.

tmpC-66_thumb[1][2]

Objective-C developers often use delegation for notification as to when an asynchronous operation is completed. In C#, delegates are similar to function pointers in C or Objective-C. In this design pattern, a class delegates another class, not known at compile time, to complete its action.

tmpC-67

Let us look at the above example, where StringDelegate is defined as a function that takes a string as a parameter and returns void. Three different delegates, writer, logger and multiLogger, are constructed by passing in methods that have the same signature as the StringDelegate declaration. This can be contrasted with Objective-C delegates, which are usually defined using protocol declaration.

Calling Writer invokes the writeString method of ConsoleLogger to print the message to the console. On the other hand, calling Logger invokes the logString method of FileLogger to log the message to the file. As you can see, delegates achieve indirection while providing type safety. Delegates may be concatenated, as shown by MultiLogger, which logs the message to both loggers.

Events

Events in C# are useful in the pub-sub design pattern. Events are a very powerful design pattern for asynchronous programming. An object can publish a set of events that subscribers in turn subscribe to.Events are built using delegates, as shown below.

tmpC-68

 

tmpC-69_thumb[2]

Summary

C# is a strongly typed, object oriented programming language that uses static binding. Many Objective-C concepts map closely to corresponding C# concepts. This topic is a quick introduction to how C# concepts map to those of Objective-C. It provides a starting point for Objective-C users and points to additional resources. Knowledge of object oriented programming, and Objective-C experience, will provide a strong foundation to enable you to master C# quickly.

Next post:

Previous post: