Wednesday, December 15, 2010

The @” syntax in Objective-C vs C#

A common mistake that I see in some of the code from our customers, or from contributed samples to the MonoMac repository is the use of the @”string” syntax in C# programs.

Summary: do not use the @”…” when porting Objective-C samples to C#.

String Syntax in Objective-C and C#

Objective-C supports two kinds of string literals in your source code, strings that are surrounded by double-quotes and strings that are prefixed with the at-sign and then double quotes.

The first kind are zero-terminated C-style strings.   For example the string “foo” is encoded by the compiler as the following four bytes: ‘f’, ‘o’, ‘o’ and zero plus the address of the string at the location where this is referenced.

The second kind, for example @”Hello World” is a CoreFoundation string, and the compiler has to encode by creating a static instance of a CoreFoundation CFString object: it has a class identifier, some object flags, a pointer to the data (‘foo’ in this case) and the length of the string.

Read more: Miguel's OSX and iOS blog

Posted via email from .NET Info