93

I work for a tech company that does more prototyping than product shipment. I just got asked what's the difference between C# and F#, why did MS create F# and what scenarios would it be better than C#.

I've been using the language for a while now and I love it so I could easily go on about the great features of F# however I lack the experience in C# to say why we should use one over the other.

What's the benefits of using C# vs F# or F# vs C#?

casperOne
  • 73,706
  • 19
  • 184
  • 253
gradbot
  • 13,732
  • 5
  • 36
  • 69
  • 4
    Seems to me that there quite a lot of questions already on SO which at least partially answer your question. Have you tried searching using "[F#] keyword" instead of "f# keyword"? ("[f#] advantages", for example) – Benjol Jun 05 '09 at 05:46

8 Answers8

86

General benefits of functional programming over imperative languages:

You can formulate many problems much easier, closer to their definition and more concise in a functional programming language like F# and your code is less error-prone (immutability, more powerful type system, intuitive recurive algorithms). You can code what you mean instead of what the computer wants you to say ;-) You will find many discussions like this when you google it or even search for it at SO.

Special F#-advantages:

  • Asynchronous programming is extremely easy and intuitive with async {}-expressions - Even with ParallelFX, the corresponding C#-code is much bigger

  • Very easy integration of compiler compilers and domain-specific languages

  • Extending the language as you need it: LOP

  • Units of measure

  • More flexible syntax

  • Often shorter and more elegant solutions

Take a look at this document

The advantages of C# are that it's often more accurate to "imperative"-applications (User-interface, imperative algorithms) than a functional programming language, that the .NET-Framework it uses is designed imperatively and that it's more widespread.

Furthermore you can have F# and C# together in one solution, so you can combine the benefits of both languages and use them where they're needed.

Dario
  • 48,658
  • 8
  • 97
  • 130
  • 16
    They combine in very weird ways. For example, you can overload the > operator in F#. C# developers can then use it. However, F# developers can't. That's right, F# can emit operator overloads that it can't consume. – Jonathan Allen Jun 08 '09 at 23:23
  • "this document" link is broken... – Eduardo Brites Jun 27 '13 at 16:24
36

It's like asking what's the benefit of a hammer over a screwdriver. At an extremely high level, both do essentially the same thing, but at the implementation level it's important to select the optimal tool for what you're trying to accomplish. There are tasks that are difficult and time-consuming in c# but easy in f# - like trying to pound a nail with a screwdriver. You can do it, for sure - it's just not ideal.

Data manipulation is one example I can personally point to where f# really shines and c# can potentially be unwieldy. On the flip side, I'd say (generally speaking) complex stateful UI is easier in OO (c#) than functional (f#). (There would probably be some people who disagree with this since it's "cool" right now to "prove" how easy it is to do anything in F#, but I stand by it). There are countless others.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • 22
    If all you have is a hammer, everything looks like a nail. -Maslow – Charlie Salts Jun 04 '09 at 19:13
  • 20
    I'm not going to up vote this because it doesn't give any real specifics except for the one data example. I know they are different tools. I'm asking what jobs these two tools are best and worst at in comparison to each other. I know a philips is often the best tool for the job even though a smaller flathead will work. – gradbot Jun 04 '09 at 20:16
  • 1
    Haha, thanks @Spencer ;) @gradbot - no problem! Sorry my answer isn't exactly what you're looking for... hopefully others will find it useful. – Rex M Jun 04 '09 at 23:53
  • 14
    If all you have is a hammer, everthing looks like a thumb. – Ed Power Feb 04 '10 at 22:13
  • 6
    i agree with gradbot, this is a good answer hence no downvote from me, however it doesn't really get to the specifics of the original questions. This answer is just a vague conceptual explanation, but really misses the point of answering the question exactly. – Stan R. Feb 04 '10 at 22:21
  • 1
    -1: Reflex downvote for "complex stateful UI is easier in OO (c#)" because way too many C# developers use Haskell to find excuses not to learn F#. If anyone has any concrete F# vs C# UI comparisons I'd love to see them. From where I'm standing, statefulness is irrelevant there but concurrency is critical and F# wipes the floor with C# when it comes to concurrent programming (async, MailboxProcessor, first-class events etc.). – J D Apr 02 '11 at 23:59
27
  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)
Rinat Abdullin
  • 23,036
  • 8
  • 57
  • 80
  • 6
    About F# having better performance than C# for math: Apparently, that's not true. See http://thoughtfulcode.wordpress.com/2010/12/30/is-f-math-really-faster-than-c/ – Joh Apr 01 '11 at 18:11
  • 3
    @Joh: `inline` is an obvious example of something that can provide massive performance improvements in F# that C# cannot express. – J D Apr 02 '11 at 23:42
  • @Jon Harrop: I was specifically referring to Rinat's blog entry. It seems the timings in favour of F# he got were due to sub-optimal C# code. – Joh Apr 04 '11 at 07:17
27

To answer your question as I understand it: Why use C#? (You say you're already sold on F#.)

First off. It's not just "functional versus OO". It's "Functional+OO versus OO". C#'s functional features are pretty rudimentary. F#'s are not. Meanwhile, F# does almost all of C#'s OO features. For the most part, F# ends up as a superset of C#'s functionality.

However, there are a few cases where F# might not be the best choice:

  • Interop. There are plenty of libraries that just aren't going to be too comfortable from F#. Maybe they exploit certain C# OO things that F# doesn't do the same, or perhaps they rely on internals of the C# compiler. For example, Expression. While you can easily turn an F# quotation into an Expression, the result is not always exactly what C# would create. Certain libraries have a problem with this.

    • Yes, interop is a pretty big net and can result in a bit of friction with some libraries.

    • I consider interop to also include if you have a large existing codebase. It might not make sense to just start writing parts in F#.

  • Design tools. F# doesn't have any. Does not mean it couldn't have any, but just right now you can't whip up a WinForms app with F# codebehind. Even where it is supported, like in ASPX pages, you don't currently get IntelliSense. So, you need to carefully consider where your boundaries will be for generated code. On a really tiny project that almost exclusively uses the various designers, it might not be worth it to use F# for the "glue" or logic. On larger projects, this might become less of an issue.

    • This isn't an intrinsic problem. Unlike the Rex M's answer, I don't see anything intrinsic about C# or F# that make them better to do a UI with lots of mutable fields. Maybe he was referring to the extra overhead of having to write "mutable" and using <- instead of =.

    • Also depends on the library/designer used. We love using ASP.NET MVC with F# for all the controllers, then a C# web project to get the ASPX designers. We mix the actual ASPX "code inline" between C# and F#, depending on what we need on that page. (IntelliSense versus F# types.)

  • Other tools. They might just be expecting C# only and not know how to deal with F# projects or compiled code. Also, F#'s libraries don't ship as part of .NET, so you have a bit extra to ship around.

  • But the number one issue? People. If none of your developers want to learn F#, or worse, have severe difficulty comprehending certain aspects, then you're probably toast. (Although, I'd argue you're toast anyways in that case.) Oh, and if management says no, that might be an issue.

I wrote about this a while ago: Why NOT F#?

MichaelGG
  • 9,976
  • 1
  • 39
  • 82
6

You're asking for a comparison between a procedural language and a functional language so I feel your question can be answered here: What is the difference between procedural programming and functional programming?

As to why MS created F# the answer is simply: Creating a functional language with access to the .Net library simply expanded their market base. And seeing how the syntax is nearly identical to OCaml, it really didn't require much effort on their part.

Community
  • 1
  • 1
Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
  • 1
    Although I think your general answer is correct that the real question is about the comparison of programming paradigms and not languages, I feel that the answer in the question you are referring is a bit shallow. – Jeroen Huinink Jun 04 '09 at 18:47
  • Feel free to suggest another question if you have a better one. That's the highest rated one I found from a google search. – Spencer Ruport Jun 04 '09 at 18:51
  • 1
    I think he was trying to be kind about you sounding like an ass for saying F# didn't require much effort on Micrsoft's part. – Matthew Whited Jun 04 '09 at 19:22
  • 1
    I don't buy into that other link answering my question. C# supports a lot of functional constructs in newer versions. – gradbot Jun 04 '09 at 20:22
  • C# vs F# != procedural vs functional. – J D Jul 02 '10 at 01:05
5

One of the aspects of .NET I like the most are generics. Even if you write procedural code in F#, you will still benefit from type inference. It makes writing generic code easy.

In C#, you write concrete code by default, and you have to put in some extra work to write generic code.

In F#, you write generic code by default. After spending over a year of programming in both F# and C#, I find that library code I write in F# is both more concise and more generic than the code I write in C#, and is therefore also more reusable. I miss many opportunities to write generic code in C#, probably because I'm blinded by the mandatory type annotations.

There are however situations where using C# is preferable, depending on one's taste and programming style.

  • C# does not impose an order of declaration among types, and it's not sensitive to the order in which files are compiled.
  • C# has some implicit conversions that F# cannot afford because of type inference.
Joh
  • 2,380
  • 20
  • 31
5

F# is not yet-another-programming-language if you are comparing it to C#, C++, VB. C#, C, VB are all imperative or procedural programming languages. F# is a functional programming language.

Two main benefits of functional programming languages (compared to imperative languages) are 1. that they don't have side-effects. This makes mathematical reasoning about properties of your program a lot easier. 2. that functions are first class citizens. You can pass functions as parameters to another functions just as easily as you can other values.

Both imperative and functional programming languages have their uses. Although I have not done any serious work in F# yet, we are currently implementing a scheduling component in one of our products based on C# and are going to do an experiment by coding the same scheduler in F# as well to see if the correctness of the implementation can be validated more easily than with the C# equivalent.

Jeroen Huinink
  • 1,947
  • 3
  • 17
  • 31
  • 4
    -1. F# is a multi-paradigm (OO+FP) language. Only **purely** functional languages don't have side-effects (like Haskell), but F# is not pure. – Mauricio Scheffer Sep 04 '10 at 20:55
5

F# is essentially the C++ of functional programming languages. They kept almost everything from Objective Caml, including the really stupid parts, and threw it on top of the .NET runtime in such a way that it brings in all the bad things from .NET as well.

For example, with Objective Caml you get one type of null, the option<T>. With F# you get three types of null, option<T>, Nullable<T>, and reference nulls. This means if you have an option you need to first check to see if it is "None", then you need to check if it is "Some(null)".

F# is like the old Java clone J#, just a bastardized language just to attract attention. Some people will love it, a few of those will even use it, but in the end it is still a 20-year-old language tacked onto the CLR.

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
  • Here's hoping the masses beat some sense into them and F# 5 will be a bit more pragmatic. – Jonathan Allen Jun 07 '09 at 06:30
  • 1
    I agree that Nullable should have the compiler do some magic aliasing for us. I'm not sure that making "Some null" be equivalent to None would always work - some interop code might rely on it. But reference null? How are you going to work around a major hole in .NET? Wrap every reference type in an option? In practise, this only seems to be an issue with certain interop scenarios. – MichaelGG Jun 10 '09 at 02:57
  • Close. Wrap every reference type in an option, unless the function returning it is marked as non-nullable by a Code Contract. .NET 4 is supposed to have all the pieces needed to do this right. – Jonathan Allen Jun 10 '09 at 19:37
  • "Wrap every reference type in an option" -- uh, that'd suck. It'd add lots of overhead and look quite disgusting. F# started in 2004 -- well before Code Contracts, which will only be in .NET 4. So that's not a real answer for us using 3.5 or Mono. – MichaelGG Jun 12 '09 at 07:04
  • 12
    FWIW, I've been coding professionally in F# for several years (longer than almost anyone else in the world) and I have never seen this problem or the code `Some null` in any F# code anywhere. Of all the things people might gripe about, this has to be *waaay* down on the list... – J D Jul 02 '10 at 01:04
  • 1
    Comparing F# to C++ is a bit far-fetched. Many parts of C++ have undefined or unclear semantics, F# is simple and well-defined. The quality of the .NET runtime can't be held against F#, since any .NET language will have the same issues. – Joh Apr 01 '11 at 18:23
  • @Joh. That isn't true, there are languages on the CLR that actually do handle nulls correctly. Spec# is one example, C# or VB w/Code Contracts is another. – Jonathan Allen Apr 02 '11 at 23:07
  • @Jonathan Allen: From the Spec# overview: "We allow interoperability with existing .NET code and libraries, but we guarantee soundness only as long as the source comes from Spec#". I interpret this as meaning that even Spec# programs could suffer null reference exceptions if the null value comes from C# code. Moreover, why couldn't the static checker and other tools from Spec# work on assemblies produced by F#? After all, the F# language does have a type annotation for nullable values. – Joh Apr 03 '11 at 10:25
  • 1
    In over 2 years of professional F# programming, like @Jon, I have never seen any problem related to 'Some null'. On the other hand, I have immensely profited from the features of the .Net framework. – Marc Sigrist Oct 02 '12 at 16:52