
Why C# is the best language for mobile development - natfriedman
http://blog.xamarin.com/eight-reasons-c-sharp-is-the-best-language-for-mobile-development/
======
jordan0day
As languages go, C# may be the ultimate "middle ground" because it really
_excels_ and providing a middling implementation of [your-favorite-language-
feature].

That is, if you're a functional programming enthusiast, you can do _a lot_ of
functional programming in C#. Sure, it's often more painful than haskell or
lisp or F#, but it's workable.

If you're a dynamic programming enthusiast, C# has a perfectly workable (but
ultimately unsatisfying) implementation of _dynamic_.

Systems programmer? Mark your code as "unsafe" and twiddle bits to your hearts
content! It's not as quick or necessarily easy as C, but it's there!

Even its' OOP, which is C#'s "official" paradigm, is probably disappointing to
smalltalk guys, but hey, it's better than Java, right?!

It's not glamorous or flashy, it's a workhorse language. And at being a
workhorse language, I'd say it really is one of "the best".

~~~
benzor
Sorry, but you're really attacking a straw man here.

Neither C# itself nor the OP's article sell C# as being a prime language for
functional, dynamic, or systems programming. Rather, it has inherited some
convenient little bits of each paradigm to make the language that much nicer
to write.

For example, don't want to redeclare that "List<List<LongTypeName>>" you're
copying over because it has a scope of 2 lines? Just dynamically type it by
calling it a "var" and be done with it. Boom: Cleaner code and zero
performance hit because the compiler infers the type such that the resulting
IL is identical at runtime.

Sure, given features can be misused to produce ugly or "unsatisfying" code,
but that's true of any language and is ultimately the programmer's fault. Just
because said features are provided, doesn't mean you need to use them. You
should ultimately be using the right tool for the job, after all. C# gives you
the power of having a wider choice of tools, and I love it.

~~~
MichaelGG
"var" is not dynamic typing. It's just a way to enable type inference - it's
still as static as can be. It also has a very limited useful scope in C#, as
type inference isn't supported in most areas.

~~~
migueldeicaza
There is only one place where the type inferencing is not supported, field
declarations. Not sure how that became "most areas".

~~~
MichaelGG
Miguel I'm confused then - your experience with Mono certainly means you have
a better understanding, but I thought I understood it pretty well, too.

Places lacking type inference:

    
    
      - Parameter definitions
      - Method return types
      - Generic type parameters (sometimes)
      - Lambda expressions (due lack of syntax to indicate quoted code)
      - Field declarations
    

The only place type inference works for declarations is in local variable
declarations and lambda parameter types if the delegate type is known.

Perhaps the definition of "most" is arguable, but C# has many places that need
you to unnecessarily specify types, and there's no good theoretical reasons
for any of it, right? (Except the whole syntax sharing for expression trees
versus anonymous functions, which is debatable.)

~~~
migueldeicaza
"var" is a shorthand to not declare the type when it can be inferred, in most
cases to avoid Foo foo = new Foo(). The point is that it avoid repetitive
typing, while still preserving type safety and everything that comes with it:
compiler checking that right types are used in the right places.

[Digression While it is possible to use in var foo = GetIt() the practice is
discouraged because it makes the type of "foo" opaque to the casual reader]

For a parameter definition, its use clearly makes no sense. What is the type
for the following method?

void Demo (var x) {}

"var" in the above example would not really add much value, neither would the
following example, where inference will oscillate from useless to fragile,
depending on who you ask:

void Demo (var x) { var j = x.Parent; }

For method return types the reason is simple, it serves no useful purpose, in
fact, it can be quite damaging as the public API contract can change during
routine work. Consider a method:

var Demo (PointF f) { if (f.X < 0) return f.X; return 1; }

The above method signature cal oscillate easily between float or double on the
day that someone changes the 1 with 1.2. Reading a diff or a patch file wont
catch the fact that you have accidentally changed the type of the function.

If this is the kind of code that you need to write (both cases above), then by
all means, use the right tool and replace "var" with "dynamic". I would argue
that using "dynamic" for the sake of not declaring the type there is a poor
practice, but I am not about to lecture you on poor coding choices.

Generic type paramters: your comment makes no sense.

Lamdba expressions: makes no sense, the parameters are already inferred. Not
sure what value (var x) adds over the already existing (x) syntax.

Which brings us to the very case I quoted "field declarations".

The ones that you skipped where it is supported: local variable declarations,
for statements, using statements, consts locals and fixed statements.

~~~
MichaelGG
Honest question: Are you just playing devil's advocate? It appears that the
reasoning for C#'s design is that it targets LINQ as a goal, and the new
features (like var and extension methods) were implemented just for the LINQ
case, not considering those features by themselves.

In fact, the lack of type inference for fields was said to be due to technical
limitations in the C# compiler implementation, not for any language reason.
[1] Sure, any product will have limitations due to schedules/resources, but
that doesn't change the fact that they're unfortunate limitations that could
be fixed. C# hasn't addresses these issues, but they've had 2 or 3 releases
since they were introduced.

>For a parameter definition, its use clearly makes no sense. What is the type
for the following method? >void Demo (var x) {}

In that case, x has no constraints (it's unused), so it's generic. Pretty
simple. An unused parameter isn't that useful outside of a few cases. Usually
you'll use the variable, and constraints can be inferred. Or you'll find a
constraint that limits the type to a concrete type. Here's some examples:

    
    
      void dub (var x) { Tuple.Create(x,x); } // x is T
      void uri (var x) { new Uri(x); } // x is string
      void cmp (var x, var y) { Nullable.Compare(x, y); } // x and y are Nullable<T> where T : struct
    

The example of "void Demo (var x) { var j = x.Parent; }" is probably one place
you'd want it to fail, because using member access to infer types can get
complicated, at least within C#'s type system. You'd want a static duck typing
system in this case like "anonymous interfaces" or something to that effect.

Arguing against return type inference is wierd: C# does that in anonymous
functions - certainly you don't think we should have to annotate types there!

As for type signatures changing, if you need want to keep public contracts,
then write them out! No one is saying you need to always infer everywhere,
just that it's a great aid. Also, this particular example just demonstrates
why C#'s type coercion is a bad idea, albeit understandable, given their
desire to follow C style.

Generic type parameters. What do you mean it makes no sense? I can't write,
e.g. "new List() { 1 }" - it complains List needs a type parameter. Another
example: "Func<var> = () => 1". Nope, I'm required to explicitly provide the
type. What if C# didn't have syntax support for Nullable<T>? You'd have to do
e.g. "x = new Nullable<int>(1)" or create a helper function like Tuple and
have e.g. "x = Nullable.Create(1)". Generic type parameter inference only
happens on methods.

Also note that C# can't infer generic type parameter constraints - you've got
to annotate them all by hand. Makes sense, I guess, because it doesn't infer
any generic type parameter definitions, either.

Lambda expressions can't be type inferred. "var x = () => 1" does not work
(CS0815). This is because of the same syntax for expression trees versus
anonymous functions. And if that was changed, you'd still need to "promote"
func somehow, due to C#'s wierd nominal typing for delegates.

Fixed statements can't be type inferred either: error CS0821: Implicitly-typed
local variables cannot be fixed.

The things you mentioned, for (and foreach), using -- those are all local
variable declarations. So we have it working for local variables, for some
generic type parameters, lambda parameter definitions (when the lambda type is
known) and lambda return types.

It's a nice start, and it makes C# far more enjoyable than some other
languages like Java. But it's still quite limited, without solid reasons.

1:
[http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-n...](http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-
no-var-on-fields.aspx)

------
king_magic
_Sigh_. Okay, let's play this game.

1\. "Cutting edge", first thing listed is asynchronous programming. Okay,
don't get me wrong, I like C#, I like the Task Parallel Library, but Grand
Central Dispatch in OS X/iOS is beautifully simple and incredibly powerful. It
does everything I need it to do.

2\. "Powerful features" - OOP. Really? And Java/Objective-C don't support
OOP/encapsulation? You can't do dependency injection in Java/Objective-C? lol.

3\. "Advanced runtime" - garbage collection. I'd rather use ARC in Objective-C
instead of depending on a garbage collector.

4\. "Reliability" – type safety. Really? And Java/Objective-C aren't type
safe? I seriously doubt that anyone considers Java or Objective-C to not be
reliable languages when it comes to type safety. This is almost laughable,
IMO.

5\. "Easy to adopt" - easy to learn. Ok, I'll give you this one over
Objective-C. But frankly, I expect a good programmer worth his salt to be able
to learn another platform, and I don't consider iOS or Android to be
conceptually more difficult than Windows.

6\. "Fast execution. C# on iOS is powered by the LLVM optimizing compiler."
Uh, I think I'd rather use Objective-C compiled with LLVM. And the bit about
"performance of a low-level language"? I don't consider Objective-C to be a
"low-level language".

7\. "Native access" - sweet, I can use some fragile interface that breaks when
Apple decides to deprecate half of their stuff. Can't wait! I love waiting for
libraries to catch up.

8\. "Portability" - this is a decent point, but let's be realistic - we're
talking "minimally portable" here. Write-once run-anywhere is a pipe dream,
IMO (at least at this point). There are always platform-specific
considerations that need to be taken, and they are not always compatible with
other platforms. But even still, this point should have been the main focus of
the article. Points 1-7 are minor compared to this.

This just doesn't feel like a serious discussion of C#'s potential for mobile
development.

 _Edit_ : just for the record, I'm not necessarily trying to refute all or
some of the OP's points. I think the original article was poorly written, and
the case for C# was poorly made. Hence my "let's play this game" comment.

~~~
pfisch
LINQ is pretty sick and if obj-c has a similar feature I have never seen it.

~~~
MatthewPhillips
Eh, disagree. It's confusing for a number of reasons, firstly because instead
of choosing the common functional names -- map, filter, reduce, flatten, etc.
they choose to go with SQL-like naming. Just an annoyance. Secondly,
Expressions are a clever hack on top of the language, but they are not
intuitive for the person using them and requires you to know too much about
the particular implementation you are using (for example, if using Microsoft's
ORM, string concantenation inside an Expression is disallowed). It's not their
fault, C# isn't really functional, and Expressions allow them to make it look
functional and have some laziness built in, but there are still enough gotchas
that make using it a pain.

~~~
MichaelGG
Is there any other quotation-based system that _doesn't_ require you to
understand the implementation? Or any language/runtime/library? SQL is
different from one DB to the next, and a lot of C APIs are not implemented
identically on all OSes.

As to the names, I'm not sure it's safe to assume that "Map" would result in
better usability than "Select", for MS's target audience.

------
taumeson
Obviously a bit one-sided (it's from Xamarin, after all) but I'm a big
believer in C# and what it offers compared to what else is out there. I think
the biggest weakness is dealing with another single-vendor-of-failure (in this
case, Xamarin themselves) in order to cross-compile to Android/iPhone.

------
azakai
> Their data shows that C# popularity grew by 2.3 percent in 2012, more than
> any other programming language during the same period.

As many pointed out when that story came out, that datapoint is highly
suspicious. There are plenty of smaller languages that have surely grown much
more than that (it's easier to grow more when you are small).

Also, the actual popularity is what really matters, not the increase. If C#
increased 2.3% from 1000 to 1023, but say Java was at 1,000,000 and stayed
there at 0% growth, then the conclusion is obvious. (Not saying those are the
numbers, the point is that actual popularity trumps a few percent of growth in
a year.)

> What accounts for the growth of C# in 2012? Well, the launch of Windows 8
> has probably played a role — C# remains the dominant language of third-party
> application development on Windows devices.

Doubtful. Windows 8's launch has been a failure, even compared to Vista
according to the latest figures. And is C# even the "dominant language" for
Windows 8? It seems JavaScript might be just as important if not more so for
Metro apps.

~~~
rprasad
C# is a dominant language for indie games: Unity, and almost all games using
the Unity engine; Magicka, Terraria, Breath of Death, Weapon of Choice, and
Sol Survivor, which use the XNA framework; Eufloria, which was originally
written in C# prior to the cross-platform release, AI War, which uses C# and
Mono, and Bastion, which uses MonoGame.

~~~
azakai
Yeah, exactly, indie games would have been a much better example than Windows
8 in that article.

------
gte910h
The vast majority of the code in most apps is not core code, it's display
code. That's STILL entirely device specific.

I think the C# advocates oversell how much it is reusable

If you STARTED with a great pile of C# code, say, running on the desktop or
server, then wanted to port that to an iOS device, then you have a point.

One big problem with non-native code is that example code is almost always
written in native code, and can be hard/impossible to get new features working
once you try to translate across the language barrier (mobile gets REALLY
finicky about when X or Y is called, especially for things like animations)

~~~
natfriedman
That's actually not what we see with our customers and their apps.

Here is a real-world example of code sharing percentages for an iOS, Android,
and Mac app written in C#: <http://lipsky.me/blog/2012/9/11/touchdraw-code-
reuse-updated>

And here is another one across iOS, Android, Mac, and Windows, also in C#:
[http://praeclarum.org/post/31799384896/icircuit-code-
reuse-t...](http://praeclarum.org/post/31799384896/icircuit-code-reuse-the-
fourth-edition)

Both of these apps are using 100% _native widgets_ for their user interface,
and I think it's fair to say that both of them are fairly UI-heavy. And yet
they average >70% code sharing.

It should also be pointed out that these apps were written from scratch. In
fact, Jon Lipsky didn't even know C# before he started writing TouchDraw (the
first app I linked).

~~~
king_magic
Not all code is created equal. That 30% that needs to be rewritten for each
device could be difficult to tune for each platform. Personally, I'd like to
see some more information on what exactly was reused.

------
MichaelGG
"Async support as a first-class feature" - that's actually a flaw. C#'s async
implementation would be better served by having e.g. a generic monad system
that allows async to be done in a library. Instead, it's another baked-in
compiler feature, like C#'s duck typing and LINQ's query operators.

Calling it "cutting-edge" is an exaggeration, too.

~~~
kvb
It's not a flaw. Arguably it's worse than having a generic mechanism, but it's
certainly not worse than having to use explicit callbacks, as in essentially
all other popular languages (and previous versions of C#).

------
wyuenho
Assuming all 8 points are valid. I still will not use MonoTouch on anything
ever because it costs $999 apiece while everything else is free.

~~~
georgemcbay
Same here. I'm not opposed to paying for quality tools even when free
alternatives exist, but I'd pay like $99 for this, not $399 (or $999).

------
RyanZAG
Please don't actually do this - or if you do this, use the C# code only for
the backend, and write the UI code natively for each platform. Nothing is
worse than a 'not quire right' 'seems almost the same but isnt' UI.

~~~
natfriedman
You have misunderstood. iOS and Android apps built using C# have access to
100% of the native API of the underlying platform. So all of the UI is fully
native. Take a look at our API documentation on iOS, for example:

<http://iosapi.xamarin.com/?link=root%3a%2fMonoTouch-lib>

You can see thousands of iOS APIs bound, including all of UIKit:
<http://iosapi.xamarin.com/?link=N%3aMonoTouch.UIKit>

------
Nitramp
What is he comparing to? Arguments #2-#5 & #7 seem to apply to Java as well,
and #6 just quotes an extremely lopsided benchmark exploiting one specific
feature of their C# implementation. Most of the arguments would apply to
Objective C too, I presume (though I haven't really used that outside of
toying around).

I'd personally expect we'll see a lot more JS for mobile apps: a terrible
language compared to C#, but a very well understood UI layer (HTML).

~~~
chc
I don't think each point is meant to show that it's better in that respect
than every other competitor. I think it's meant to be sort of like those
feature grids on software packaging, where some of the competitors may have
some combination of the features, but only Our Product has the complete set.

------
erick23
Read this article for me to waste time because a programmer that program in a
programming language that dominates more he soon comes to post here trying to
convince others to learn the same...

------
erick23
after not ashamed to post an article saying that C# is the best language for
developing mobile ... must have little shame .. I'm sure you still not
programs Naive Code Android, HTML5 + CSS3 and other top mobile development
languages

------
corresation
While a bit of an aside, personally I find LINQ to have been a horrendous
misstep in the evolution of the language. While the argument that it makes
code more concise and easy to maintain holds in the small, once a project
grows it becomes a terrible cancer -- everything becomes an amorphous blob of
stuff, unintuitive, performance-disaster LINQ filters applied everywhere to
bend it into shape.

~~~
sourc3
Yes, but it's not specific to LINQ or MS or C#. If you give a tool to mediocre
developers to make things easier they will use it right away. If you don't
supervise its usage (how it fits into the architectural goals of the project
you are on) you will end up with a mess.

Anonymous methods, unnamed classes, try catch blocks are all examples of these
type of tools that when used improperly will kill the system performance, code
readability, maintainability and extensibility.

~~~
corresation
_Yes, but it's not specific to LINQ or MS or C#_

We are specifically talking about C#. LINQ was specifically held as one of the
improvements to the language. I am not quite sure what your point is relative
to that.

There are shockingly few examples where LINQ is superior to alternatives. LINQ
is the brute force technique of avoiding proper collections/algorithms.

~~~
abolibibelot
I don't understand. Are you saying that map, filter, reduce and al. on lazy
sequences in functional languages are inferior to loops, or that Python list
comprehensions and generators are inferior to loops? That's basically LINQ to
objects.

Maybe you're refering to LINQ-to-whatever (LINQ to SQL, etc.), a LINQ
generalization where you can quote your expressions, rewrite the AST and emit
something else (a very constrained kind of macros, if you will).

MS is probably to blame here, but people keep conflating the two.

~~~
corresation
In the vast majority of cases it is nothing more than syntactical sugar around
loops. And no, I'm not saying that loops are superior, but rather I'm saying
that loops are usually a terrible solution, but LINQ has a way of essentially
hiding those egregious violators.

Take a block of code with LINQ in it and rewrite it minus LINQ but logically
performing the same operations that the sugar is resolving to. To most
developers it would offend the sensibilities of construction, but somehow in
LINQ-land all seems fine.

~~~
NateDad
95% of the time, what looks like a failed "loops 101" test actually doesn't
matter at all. Maybe your list comparison function takes O(n^2) time... if
your list never gets above 10-20 objects, who cares? Yes, if you're running
LINQ over a list of 1,000,000 items, then you'll want to be careful what
you're calling. But how often does that really happen in mobile apps?

What LINQ does is make your code more concise and readable. It makes it easier
to find bugs and easier to understand by someone else (even if someone else is
you, 6 months down the road).

It also just takes a lot less time to write.

~~~
jaegerpicker
Depends on what kind of mobile apps you are writing. Most of the apps I've
worked on written tend to deal with video/ pixel level image conversions. In
these cases it's really common to say convert an rgb pixel array to yuv or
simliar and a linq expression on one of those arrays would quite simply kill
the app. Which I think is the best counter argument to the op. C# might be
fine until you decide to do something beyond the normal performance wise. Then
you are back to square one learning the native supported tools, IMO you are
much better off learning the native environments from the ground up.

~~~
corresation
This is really the crux of it. The counterargument essentially seems to be
that such broad abstractions are fine in the small or when you have enough
hardware, however that in no way carries over to smartphones where you want to
do the most with the least, and even where you have a kick-ass processor and
multi-GB RAM, you still want to reserve battery. The primary reason Android
seems to need so much more hardware than iOS can be attributed to this. Even
when you have powerful hardware, this can kill you in the large (which was the
original failure of Windows Vista -- people forget that Microsoft did a
complete revert after thousands of man years of work)

------
martinced
Mobile development issue is not the language. It's the API.

And how would using C# help me deal with the fragmentation issue ?

~~~
migueldeicaza
It does not.

And nobody claimed it did.

------
martinced
I can't stress enough how I think being able to do SQL queries is a must have
for cellpones.

Because we all know all the top-selling iPhone / Android apps do ship with an
embedded SQL DB right!?

